How to MagicMock a list of object with method and get assert count

1.4k views Asked by At

I am new to unit testing in python with MagicMock. I have the following code to assert the correct method count in python:

 def methodFoo(self):
       for booObject in self.booObjectList:
            booObject.shooMethod()

I wish to perform an assertion call count of the method shooMethod() in my unit test code to see if for N objects in booObjectList it performs N calls. The above function is not my unit test code. It is a method to be tested by creating a new method test_methodFoo() in my unit test class. How do I go about it? Thanks for you help.

2

There are 2 answers

2
Adam Smith On BEST ANSWER

Mock objects have an attribute called that tracks whether a Mock has been called, and an attribute call_count that tracks how many times they were called.

def test_methodFoo(self):
    self.object_under_test.methodFoo()
    self.assertTrue(all([booObject.shooMethod.called for
                         booObject in self.object_under_test.booObjectList]))

Note however that you can't do something like:

for o in list_of_four_o_mocks:
    o.mocked_method()
self.assertEqual(o.mocked_method.call_count, 4)

since o is a new object each time.

1
hspandher On

As Adam Smith has already answered your question, just a personal advice - I too faced lot of issues working with mock library when I started doing mocking. Besides python-mock does not works for other teating clients like pytest etc. So I recommend you to use fudge library. It is more pythonic and works with all testing clients.