dar*_*sky 4 python unit-testing mocking python-mock
我在Python 2.7中使用Mock(http://mock.readthedocs.org/en/latest/)库.我有一个main函数调用我试图测试的一些其他函数.
它调用的其他函数是其他实例方法(例如,def _other_function(self, a, b).
我正在调用我的main函数,我还有其他函数,它调用了补丁.我刚刚添加autospec=True到补丁中.但是当我检查调用参数时,它会显示一个self参数(如预期的那样):
python2.7> _other_function_mock.call_args_list
[call(<some.module.class.method object at 0x9acab90>, 1, 2)]
Run Code Online (Sandbox Code Playgroud)
在设置之前autospec=True,它只会显示我实际传递的参数(1和2).从现在调用args显示引用self,我不能只调用mock_object.assert_any_call(1, 2).我需要从中挑选出来mock_object.call_args_list并进行比较.
有没有办法仍然调用,mock.assert_any_call而不必手动选择参数来检查传递的参数是否正确?
或者,我是否可以采取更好的方法来修补实例方法?
Mic*_*ico 10
基本上有两种方法可以解决补丁的self参考问题autospec=True.
mock.ANY忽略第一个参数patch.object而不是修补静态方法引用.无论如何2无法在所有情况下使用,有时你不能在测试方法上下文中拥有对象实例; 而且这种方式往往使测试不那么清晰和复杂.我总是喜欢在我的测试中使用1:
@patch("my_module.MyClass.my_method", autospec=True)
def test_my_test(self, mock_my_method):
my_module.MyClass().my_method(1,2)
mock_my_method.assert_any_call(mock.ANY, 1, 2)
Run Code Online (Sandbox Code Playgroud)