self.
self.

Reputation: 1742

Setting mocked method return value when called with specific parameters

I have a test that works by mocking out the web service. I have it where it returns a specific return value when a specific method is called. I'm verifying that the wrapped function returns the value I expect. Issue is that the test seems almost useless.

Here is what I have -

@patch('run.Client')
def test(self, mock_client):
    service = WebService()
    mock_client.return_value.service.GetMemberStatus.return_value = 'E'
    member_status = service.get_member_status(11)
    self.assertEqual('E', member_status)

What I'm looking to do is only return E if the GetMemberStatus method is called with specific parameters. I've tried to do -

mock_client.return_value.service.GetMemberStatus(11, '', '').return_value = 'E'

however this doesn't seem to change anything.

Question - How can I set a mocked methods return value only if called with appropriate parameters?

Upvotes: 0

Views: 4954

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121524

Generally speaking, you don't. You instead assert that your mocked method has been called with the expected parameters as part of your test:

gms_mock = mock_client.return_value.service.GetMemberStatus
gms_mock.return_value = 'E'

member_status = service.get_member_status(11)

self.assertEqual('E', member_status)
gms_mock.assert_called_with(11, '', '')

All your attempt did was record a mock call, as if the code-under-test had called GetMemberStatus, then assigned 'E' on the return_value attribute of the Mock instance returned by that call.

You could set the side_effect attribute to a function instead; it'll be passed the arguments and you could test there:

def gms_mock_call(*args):
    assert args == (11, '', '')
    return 'E'

mock_client.return_value.service.GetMemberStatus.side_effect = gms_mock_call

but that really puts testing what arguments are passed in in the wrong location.

Upvotes: 3

Related Questions