[英]Python Mocking assert_called not working
我能夠成功模擬一個函數,我確信原來沒有被調用。 我在原始函數中添加了一個巨大的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)]
然而斷言仍然失敗
通常這樣的錯誤是不修補正確位置的結果。 嘗試使用以下方法修補對象本身:
@patch.object(MyObj, "helper_function")
def test_simple(mock_hf):
...
由於MyObj(假設是)在測試文件的頂部導入,因此可以直接在該對象上修補該方法。
問題是我正在檢查是否mock_hf.helper_function
,但是mock_hf
已經映射到helper_function
。 我或多或少地檢查調用了helper_function.helper_function
而不僅僅是helper_function
。
斷言行必須是mock_hf.assert_called()
我看到原來的海報已經做到了這一點,但對於其他任何絆倒這個的人都像我一樣......
不要忘記你需要將你期望的調用包裝在一個call
對象中,例如
mock_logger.assert_has_calls([call(expected_log_message_1), call(expected_log_message_2)])
如果你不這樣做,它會抱怨預期的呼叫沒有發生,你會花費多年時間比較輸出,試圖找出原因(就像我做的那樣!)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.