【问题标题】:Python Mocking assert_called not workingPython Mocking assert_call 不起作用
【发布时间】:2017-10-24 15:10:40
【问题描述】:

我能够成功地模拟一个函数,并且我确信原始函数没有被调用。我在原始函数中添加了一个巨大的 print 语句,当我模拟它时,这个 print 没有被调用。当我重新打开模拟时,不会调用 print 语句。

但是,我的 assert_call 没有说它从未被调用过。有没有人经历过这样的事情?

class FooTestCase(unittest.TestCase):

    @mock.patch('MyObj.helper_function')
    def test_simple(self, mock_hf):

        my_obj = MyObj()

        # internally, this class imports HelperModule 
        # and the method calls helper_function
        my_obj.do_something()

        mock_hf.helper_function.assert_called()

        return

我的错误回复

AssertionError: Expected 'helper_function' to have been called.

更新 我刚刚在断言之前添加了以下几行

    print mock_cw.method_calls
    print mock_cw.mock_calls

method_calls 是一个空列表,而 mock_calls 是一个包含 1 项的列表

[call(arg1_expected_for_helper_fn, arg2_expected_for_helper_fn)]

但断言仍然失败

【问题讨论】:

  • My_Obj.do_something() 是否调用了 My_Obj.helper_function()?你能把那个代码的sn-p也放上来吗?
  • 是的,确实如此。我在评论中提到了这一点。该代码非常简单,我不知道这是否会有所帮助。看看我要用什么来更新问题。这可能会有所帮助。

标签: python python-2.7 unit-testing mocking


【解决方案1】:

通常这样的错误是由于没有修补正确的位置造成的。尝试用这个来修补对象本身:

@patch.object(MyObj, "helper_function")
def test_simple(mock_hf):
    ...

由于 MyObj 是(假设是)在测试文件的顶部导入的,这会直接修补该对象上的方法。

【讨论】:

  • 虽然通常是任何补丁相关问题的正确答案,但这是我如何调用 assert 方法的问题
  • 啊,我明白了,这样就行了!
【解决方案2】:

问题是我正在检查是否调用了mock_hf.helper_function,但mock_hf 已经映射到helper_function。我或多或少检查了 helper_function.helper_function 是否被调用,而不仅仅是 helper_function

断言行需要是 mock_hf.assert_called()

【讨论】:

    【解决方案3】:

    我看到原始海报已经这样做了,但是对于其他像我一样绊倒的人......

    不要忘记您需要将预期调用包装在 call 对象中,例如

    mock_logger.assert_has_calls([call(expected_log_message_1), call(expected_log_message_2)])

    如果你不这样做,它会抱怨没有发生预期的调用,你将花费很长时间比较输出来尝试找出原因(就像我做的那样!)。

    【讨论】:

      猜你喜欢
      • 2021-12-03
      • 2021-11-22
      • 1970-01-01
      • 2018-06-27
      • 2018-05-21
      • 2012-02-15
      • 2017-05-24
      • 2015-10-25
      • 2015-10-08
      相关资源
      最近更新 更多