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
So what is the difference between them? MagicMock is a subclass of Mock . It contains all magic methods pre-created and ready to use (e.g. __str__ , __len__ , etc.). Therefore, you should use MagicMock when you need magic methods, and Mock if you don't need them.
This, along with its subclasses, will meet most Python mocking needs that you will face in your tests. The library also provides a function, called patch() , which replaces the real objects in your code with Mock instances.
Mocking is simply the act of replacing the part of the application you are testing with a dummy version of that part called a mock. Instead of calling the actual implementation, you would call the mock, and then make assertions about what you expect to happen.
side_effect: A function to be called whenever the Mock is called. See the side_effect attribute. Useful for raising exceptions or dynamically changing return values. The function is called with the same arguments as the mock, and unless it returns DEFAULT , the return value of this function is used as the return value.
@patch('call_me') def test_func(self,mock_call_me): self.assertEqual(func(),None) self.assertEqual(mock_call_me.call_count, 2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With