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

Preset input for Unit tests in Python 3

正在尝试解决 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