test a function called twice in python
43,314
Solution 1
@patch('call_me')
def test_func(self,mock_call_me):
self.assertEqual(func(),None)
self.assertEqual(mock_call_me.call_count, 2)
Solution 2
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)])
Solution 3
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/
Solution 4
@patch('call_me')
def test_func(self,mock_call_me):
self.assertEqual(func(),None)
assert mock_call_me.call_count == 2
Author by
Ksc
Updated on July 09, 2022Comments
-
Ksc almost 2 years
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
-
ChaseHardin over 4 yearsGreat solution! So much better than just asserting the call count. I appreciate the help!
-
Luke almost 3 yearsThis 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 usingself.assertEqual(mock_call_me.call_count, 2)
as mentioned above.