Fix Python – Assert that a method was called in a Python unit test


Asked By – Mark Heath

Suppose I have the following code in a Python unit test:

aw = aps.Request("nv1")
aw2 = aps.Request("nv2", aw)

Is there an easy way to assert that a particular method (in my case aw.Clear()) was called during the second line of the test? e.g. is there something like this:

assertMethodIsCalled(aw.Clear, lambda: aps.Request("nv2", aw))

Now we will see solution for issue: Assert that a method was called in a Python unit test


I use Mock (which is now unittest.mock on py3.3+) for this:

from mock import patch
from PyQt4 import Qt

@patch.object(Qt.QMessageBox, 'aboutQt')
def testShowAboutQt(self, mock):

For your case, it could look like this:

import mock
from mock import patch

def testClearWasCalled(self):
   aw = aps.Request("nv1")
   with patch.object(aw, 'Clear') as mock:
       aw2 = aps.Request("nv2", aw)

   mock.assert_called_with(42) # or mock.assert_called_once_with(42)

Mock supports quite a few useful features, including ways to patch an object or module, as well as checking that the right thing was called, etc etc.

Caveat emptor! (Buyer beware!)

If you mistype assert_called_with (to assert_called_once or assert_called_wiht) your test may still run, as Mock will think this is a mocked function and happily go along, unless you use autospec=true. For more info read assert_called_once: Threat or Menace.

This question is answered By – Macke

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0