0

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?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the answer as well as alternative ways. I poured over mocking documentations, but wasn't looking for the right terms. In addition, I found you can replace the gms_mock_call method with a lambda - gms_mock.side_effect = lambda *args: 'E' if args == (11, '', '') else None. Not sure how I feel about that, though. Will have to play with it.
Turns out pep8 throws error E731 if you assign a lambda expression. Thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.