mocking - 为什么 assert_Called_with 无法通过?

标签 mocking patch python-2.6

我在设置单元测试时遇到很多困难。我一直在使用补丁,但它的行为并不完全符合预期。

我的测试函数顶部有一个装饰器: @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.


  • 来自 https://docs.python.org/3/library/unittest.mock.html

  • 文档有点狡猾,因为他们没有在 assert_called_with 方法下提到这一点。

    我最终使用 assert_any_call 方法进行测试。

    关于mocking - 为什么 assert_Called_with 无法通过?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40987145/

    相关文章:

    c# - Drawing.Image 不允许在起订量或单元测试中使用?

    c++ - 关于模拟系统调用的建议

    .net - TDD 入门?

    git - 在 git repo 中维护我的补丁

    patch - 在偶数和奇数场景中,每 block 海龟的填充量有何差异?

    php - 如何重置对 PHPUnit 模拟对象的期望

    dll - 修补可执行文件以避免崩溃

    python - 如何优化 Python 中大型(75,000 项) bool 值集的操作?

    python - 如何从代码中随机选择一行而不重复

    python - 匹配逗号分隔的键=值列表的正则表达式,其中值可以包含逗号