-1

I am new to unit testing and I am trying to write unit test using patch.object to mock the function calls. The mocked function getObj() is called twice in the function which I am testing. First time when its called I am expecting None as return_value and second time I am expecting some_string. I am not getting how to do it.

The code is as follows:

def test_create(self):
    with contextlib.nested(
        patch.object(agent, 'try_connect',
        patch.object(util, 'get_obj', return_value = None),
        ) as (mock_try_connect, mock_get_obj):
        proxy_info = self.util.create(data)

I tried using side_effects, and give it as input to return_value but every time its returning None.

mock_value=Mock()
mock_value.side_effect = [None, 'some_string']
patch.object(util, 'get_obj', return_value = mock_value())
  • Why are you using a set as the `side_effect`? Surely you want something *ordered*? Could you expand on *"not working correctly"*? – jonrsharpe Jan 28 '16 at 10:03
  • @jonrsharpe The `side_effect` solution I founded out from some other answer here. Not working properly means, everytime when the call is made to `get_obj` its return value is `None'. – Gandharva S Murthy Jan 28 '16 at 10:19
  • Then edit the question to say that. You probably want a list, not a set. And which *"other answer"*? – jonrsharpe Jan 28 '16 at 10:21
  • @jonrsharpe its not working with list too. The other answer which I referred is from [http://stackoverflow.com/questions/24897145/python-mock-multiple-return-values?rq=1] – Gandharva S Murthy Jan 28 '16 at 10:23

1 Answers1

0

Use assert_has_calls to verify the mocked out object is being called exactly how you expect it to be called. This will help you debug your issue.

def test_create(self):
    with contextlib.nested(
            patch.object(agent, 'try_connect',
            patch.object(util, 'get_obj', side_effect = [None, 'some_string']),
            ) as (mock_try_connect, mock_get_obj):
        proxy_info = self.util.create(data)
        mock_try_connect.assert_has_calls([mock.call(#params), ...])
        mock_get_obj.assert_has_calls([...])

Now once you've debugged the issue you can delete the last two statements since they add nothing to your test coverage and make your code harder to maintain.

Dan
  • 1,874
  • 1
  • 16
  • 21