Python 3中单元测试的预设输入
试图用Python解决一个在线编码问题,提交所需的I/O很简单Python 3中单元测试的预设输入,python,unit-testing,io,mocking,stubbing,Python,Unit Testing,Io,Mocking,Stubbing,试图用Python解决一个在线编码问题,提交所需的I/O很简单input()和print()。由于我很懒,不想为了运行单元测试而用方法参数替换I/O,我该如何创建一个单元测试,允许我替换一个预设字符串作为输入?例如: class Test(TestCase): __init__(self): self.input = *arbitrary input* def test(self): c = Class_Being_Tested()
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()
。您可以在文档中了解更多信息:在您的示例中:
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,您还可以创建一个fixture并将其与autouse
一起自动使用。请在此查看一个示例: