模拟变量的功能

Dan*_*son 6 python unit-testing mocking

对于单元测试,我想在函数内部模拟一个变量,例如:

def function_to_test(self):
    foo = get_complex_data_structure()  # Do not test this
    do_work(foo)  # Test this
Run Code Online (Sandbox Code Playgroud)

我的单元测试,我不想依赖于get_complex_data_structure()返回的内容,因此想要手动设置foo的值.

我该如何做到这一点?这是适合的地方@patch.object吗?

mgi*_*son 11

假设 get_complex_data_struct 是一个函数1,您可以使用任何各种mock.patch 实用程序对其进行修补:

with mock.patch.object(the_module, 'get_complex_data_structure', return_value=something)
  val = function_to_test()
  ...
Run Code Online (Sandbox Code Playgroud)

它们可以用作装饰器或上下文管理器,或者使用startstop方法显式启动和停止。2


1如果它不是一个函数,您总是可以将该代码分解为一个简单的实用函数,该函数返回复杂的数据结构
2有一百万种使用模拟的方法 - 阅读文档以找出所有方法是值得的可以设置返回值等


Mar*_*ers 8

只是@patch()用来嘲笑get_complex_data_structure():

@patch('module_under_test.get_complex_data_structure')
def test_function_to_test(self, mocked_function):
    foo_mock = mocked_function.return_value
Run Code Online (Sandbox Code Playgroud)

当测试函数然后调用get_complex_data_structure()模拟对象时,返回并存储在本地名称中foo; mocked_function.return_value在上述测试中引用的相同对象; 例如,您可以使用该值来测试是否do_work()传递了正确的对象.

  • @chintan-p-bhatt:然后将 [`Mock.side_effect`](https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.side_effect) 设置为可迭代的(Python 将在每次调用时使用该可迭代对象的下一个值)或函数;函数被赋予相同的参数,因此您可以根据这些参数返回一个值。 (2认同)