Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/79.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3中单元测试的预设输入_Python_Unit Testing_Io_Mocking_Stubbing - Fatal编程技术网

Python 3中单元测试的预设输入

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()

试图用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()
。您可以在文档中了解更多信息:在您的示例中:

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
一起自动使用。请在此查看一个示例: