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)
它们可以用作装饰器或上下文管理器,或者使用start和stop方法显式启动和停止。2
1如果它不是一个函数,您总是可以将该代码分解为一个简单的实用函数,该函数返回复杂的数据结构
2有一百万种使用模拟的方法 - 阅读文档以找出所有方法是值得的可以设置返回值等
只是@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()传递了正确的对象.
| 归档时间: |
|
| 查看次数: |
13748 次 |
| 最近记录: |