繁体   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