78

I have the following function which is called twice

def func():
    i=2
    while i
       call_me("abc")
       i-=1

I need to test this function whether it is called twice. Below test case test's if it called at all/many times with given arguments.

@patch('call_me')
def test_func(self,mock_call_me):
    self.val="abc"
    self.assertEqual(func(),None)
    mock_call_me.assert_called_with(self.val)

I want to write a test case where "mock_call_me.assert_called_once_with("abc")" raises an assertion error so that i can show it is called twice.

I don't know whether it is possible or not.Can anyone tell me how to do this?

Thanks

1

4 Answers 4

123
@patch('call_me')
def test_func(self,mock_call_me):
  self.assertEqual(func(),None)
  self.assertEqual(mock_call_me.call_count, 2)
Sign up to request clarification or add additional context in comments.

Comments

66

You can even check parameters passed to each call:

from mock import patch, call

@patch('call_me')
def test_func(self, mock_call_me):
    self.val="abc"
    self.assertEqual(func(),None)
    mock_call_me.assert_has_calls([call(self.val), call(self.val)])

2 Comments

This method will still pass even if mock_call_me has been called more than twice. If you'd like to assert parameters and number of calls, make sure to also validate call-count using self.assertEqual(mock_call_me.call_count, 2) as mentioned above.
I combined both methods to validate that it was called with specific parameters and that it was only called twice: mock_call_me.assert_has_calls([call(self.val1), call(self.val2)]) self.assertEqual(mock_call_me.call_count, 2)
14
@patch('call_me')
def test_func(self,mock_call_me):
    self.assertEqual(func(),None)
    assert mock_call_me.call_count == 2

Comments

1

I know that if you use flexmock then you can just write it this way:

flexmock(call_me).should_receive('abc').once() flexmock(call_me).should_receive('abc').twice()

Link: http://has207.github.io/flexmock/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.