Python Mocking assert_called不起作用

问题描述 投票:2回答:3

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

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

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)]

然而断言仍然失败

python python-2.7 unit-testing mocking
3个回答
1
投票

通常这样的错误是不修补正确位置的结果。尝试使用以下方法修补对象本身:

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

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


2
投票

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

断言行必须是mock_hf.assert_called()


0
投票

我看到原来的海报已经做到了这一点,但对于其他任何绊倒这个的人都像我一样......

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

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

如果你不这样做,它会抱怨预期的呼叫没有发生,你会花费多年时间比较输出,试图找出原因(就像我做的那样!)。

© www.soinside.com 2019 - 2024. All rights reserved.