簡體   English   中英

在模擬函數上調用 assert_called_with 時出現問題

[英]Problem calling assert_called_with on mocked function

我有一個問題,我想在模擬函數上調用 assert_called_with 函數,但我模擬的函數似乎缺少模擬對象的典型屬性。

def mock_get(address):
   class Response():
       def __init__(self):
           self.status_code = 200
       def json(self):
           dict= {"key":value}
           return json.dumps(dict)
        r = Response()
        return r
with mock.patch.object(requests, 'get', new=mock_get): 
    #call function that uses requests.get
    mock_get.assert_called_with(address)

嘗試在 mock_get 上調用 assert_call_with 會給我一個屬性錯誤,說明 mock_get 沒有名為 assert_call_with 的函數。 有沒有辦法使用這個功能而不必事先使用@patch?

沒有正確嘲笑。

像這樣嘗試:

with mock.patch("path.to.requests.get") as get:
    get.status_code = 200
    get.json.return_value = {"test_key": "test_value"}
    # call function that uses requests.get
    get.assert_called_once_with("htttps://www.example.org/")

"path.to.requests.get"是查找請求的地方。 例如,如果您調用的函數是在"./myproject/mymodule.py"的模塊中定義的,那么您應該在"myproject.mymodule.requests.get"處打補丁。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM