简体   繁体   中英

Mocking inner object call

Here is my code that is under test -

client = Client('http://www.w3schools.com/webservices/tempconvert.asmx')
client.service.CelsiusToFahrenheit('1234')

Here is my test -

@patch.object(Client.service, 'CelsiusToFahrenheit')
def test_method_call(self, mock):
    converted = convert('1234')
    mock.assert_called_once_with('1234')

I'm trying to mock using patch.object the CelsiusToFahrenheit() method call, however I keep getting exceptions that say AttributeError: type object 'Client' has no attribute 'service' . I've tried many variations and everything fails with similar exceptions.

My goal is to ensure CelsiusToFahrenheit() gets called with the appropriate parameter, 1234. How can I make this happen?

Alternatively, are there any other ways of achieving this? Would using Mock instead be more appropriate?

You're patching the wrong thing, it looks like you don't need patch.object but just the usual patch.

@patch('path.where.Client.imported.Client.service.CelsiusToFahrenheit')
def test_method_call(self, mock):
    converted = convert('1234')
    mock.assert_called_once_with('1234')

Additionally make sure the path through which the CelsiusToFahrenheit method is imported (via convert here) is where you're patching, as opposed to the path where the CelsiusToFahrenheit method is defined (see where to patch ).

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