我在设置单元测试时遇到很多困难。我一直在使用补丁,但它的行为并不完全符合预期。
我的测试函数顶部有一个装饰器:
@mock.patch('WarningFactory.WarningAPIUpdate')
@mock.patch('WarningFactory.SomethingElse')
def test_send_tc_update(self, other_mock, api_mock):
但是,当我尝试做出以下断言时,在我的函数结束时:api_mock.send_warning.assert_called_with('IDQ20026', 'IDQ20026')
它失败
我知道那应该通过,因为我跑了print api_mock.mock_calls
给予[call(u'test_api'),
call().send_warning('IDQ20026', 'IDQ20026'),
call().send_warning('IDQ24500', 'IDQ24500')]
我可以清楚地看到使用正确值调用的 send_warning 方法,那么为什么我的断言失败了?
最佳答案
现在回想起来,问题是 assert_call_with 只检查最近的调用。
assert_any_call(*args, **kwargs)¶ assert the mock has been called with the specified arguments.
The assert passes if the mock has ever been called, unlike assert_called_with() and assert_called_once_with() that only pass if the call is the most recent one, and in the case of assert_called_once_with() it must also be the only call.
文档有点狡猾,因为他们没有在 assert_called_with 方法下提到这一点。
我最终使用 assert_any_call 方法进行测试。
关于mocking - 为什么 assert_Called_with 无法通过?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40987145/