本文介紹了如何在 Python 中對象的模擬方法中調用 self?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我嘗試測試一些不返回任何內容但將結果保存到數據庫的代碼.通過模擬 save 方法,我希望檢查事情是否已正確處理:
I try to test some codes which don't return anything but save the result to the DB. By mocking the save method, I wish to check whether things have been processed correctly:
def mock_save(self):
assert(self.attr, 'dest_val')
with mock.patch.object(Item, "save", create=True) as save:
save.side_effect = mock_save
func_to_call() //in func_to_call, I call item.save()
但是,這似乎是不允許的.它表示參數的數量不匹配.
However, it seems that this is not allowed. It says that the number of argument mismatch.
如果我執行 def mock_save()
,它將不起作用.
If I do def mock_save()
, it won't work.
我如何才能引用模擬方法所作用的對象?(我在另一個適用于 __init__
方法的線程中看到它可以直接從類中調用).
How can I have a reference to the object which the mock method act upon too? (I saw it in another thread that is applicable to __init__
method which can be called directly from the class).
推薦答案
你需要 autospec=True
def mock_save(self):
assert self.attr == 'dest_val'
with mock.patch.object(Item, "save", autospec=True) as save:
save.side_effect = mock_save
func_to_call()
這篇關于如何在 Python 中對象的模擬方法中調用 self?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!