如果我們呼叫 main 方法run呼叫我感興趣的方法 - self.get_request() ,是否可以使用呼叫該方法的哪些引數以及它回傳的結果來檢查測驗。
檔案.py
class A:
def run():
some logic...
request = self.get_request()
some logic...
return response
測驗.py
from file.py import A
def test():
"""
Inside this test, I want to check the parameters and the value returned by the
get_request method, but I don't want to check it separately
I want to check it by calling the parent method - run
"""
instance = A()
response = instance.run()
assertions logic for instance.get_request..
我知道可以模擬一個方法,然后我們可以訪問呼叫次數、引數等。如果我的要求可以通過模擬以某種方式實作,我只想補充一點,我的模擬必須與它模擬的方法具有相同的邏輯(相同)。
uj5u.com熱心網友回復:
您所要求的可能是wraps可以在 補丁中使用的引數- 這允許您模擬一個函式,同時它仍然保留以前的(或其他一些)功能(請注意,引數本身在Mock下描述)。與任何模擬一樣,這確實允許您測驗呼叫和呼叫 args,但不允許您檢查函式的回傳值。這必須通過其副作用進行測驗(在您的情況下,通過回傳response的應該取決于 的回傳值get_request)。
這是您的案例的說明:
from unittest import mock
class A:
def run(self):
request = self.get_request(21)
return request
def get_request(self, foo):
return foo * 2
def test_run():
instance = A()
with mock.patch.object(instance, "get_request", wraps=instance.get_request) as mocked:
assert instance.run() == 42
mocked.assert_called_once_with(21)
在這種情況下,模擬呼叫真實get_request方法并回傳其結果,同時記錄呼叫和呼叫引數。
我為演示添加了一些引數get_request,并直接回傳了呼叫的結果run——在你的情況下,這當然會有所不同,但想法應該是一樣的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/438725.html
上一篇:使用Mockito跳過方法執行
下一篇:如何在django中測驗上傳檔案
