正在尝试用 Python 解决在线编码问题,提交所需的 I/O 很简单 input() 和 print()。由于我很懒,不想用方法参数替换 I/O 以运行单元测试,我将如何创建一个允许我替换预设字符串作为输入的单元测试?例如:
class Test(TestCase):
__init__(self):
self.input = *arbitrary input*
def test(self):
c = Class_Being_Tested()
c.main()
...make self.input the required input for c.main()
...test output of c.main()
请您参考如下方法:
您可以使用 mock.patch() 来修补对任何对象的调用。在这种情况下,这意味着修补 input()。您可以在文档中阅读更多相关信息:https://docs.python.org/dev/library/unittest.mock.html在你的例子中:
import mock
class Test(TestCase):
@mock.patch('builtin.input')
def test_input(self, input_mock):
input_mock.return_value = 'arbitrary string'
c = Class_Being_Tested()
c.main()
assert c.print_method.called_with('arbitrary string') #test that the method using the return value of input is being called with the proper argument
请注意,如果您使用的是 pytest,您还可以创建一个夹具并通过 autouse 自动使用它。在此处查看示例:http://pythontesting.net/framework/pytest/pytest-fixtures-nuts-bolts/#autouse
