简体   繁体   中英

Problem calling assert_called_with on mocked function

I have a problem where I want to call the assert_called_with function on a mocked function, but the function I am mocking seems to be missing the typical properties of a mocked object.

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)

Attempting to call assert_called_with on mock_get gives me an Attribute Error saying that mock_get doesn't have a function called assert_called_with. Is there a way to use this function without having to use @patch beforehand?

Not mocking correctly.

Try like this:

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/")

The "path.to.requests.get" is where the request is looked up. For example, if the function you're calling is defined in a module at "./myproject/mymodule.py" then you should patch at "myproject.mymodule.requests.get" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM