本文介紹了斷言未使用 Mock 調用函數/方法的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我正在使用 Mock 庫來測試我的應用程序,但我想斷言某些函數沒有被調用.模擬文檔談論像 mock.assert_call_with
和 mock.assert_called_once_with
這樣的方法,但我沒有找到像 mock.assert_not_call
這樣的東西或與之相關的東西驗證 mock 是否未調用.
I'm using the Mock library to test my application, but I want to assert that some function was not called. Mock docs talk about methods like mock.assert_called_with
and mock.assert_called_once_with
, but I didn't find anything like mock.assert_not_called
or something related to verify mock was NOT called.
我可以使用類似以下的內容,盡管它看起來既不酷也不像 Python:
I could go with something like the following, though it doesn't seem cool nor pythonic:
def test_something:
# some actions
with patch('something') as my_var:
try:
# args are not important. func should never be called in this test
my_var.assert_called_with(some, args)
except AssertionError:
pass # this error being raised means it's ok
# other stuff
任何想法如何做到這一點?
Any ideas how to accomplish this?
推薦答案
這應該適用于您的情況;
This should work for your case;
assert not my_var.called, 'method should not have been called'
樣品;
>>> mock=Mock()
>>> mock.a()
<Mock name='mock.a()' id='4349129872'>
>>> assert not mock.b.called, 'b was called and should not have been'
>>> assert not mock.a.called, 'a was called and should not have been'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: a was called and should not have been
這篇關于斷言未使用 Mock 調用函數/方法的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!