It's easy for mocks to get out of hand and I've seen tests that have many mocks and patches. That in itself is bad enough, but I want to make sure that each mock is there for a reason. Over time tests get been copy and pasted or underlying code has changes - meaning mocks exist but are no longer used.

You can do this my asserting that each mock is called in the test. I've seen tests with that end up being 4 lines of mocks, a call, then 4 lines of checking the mocks are being called. Clearly, something was going wrong with those tests in the first place.

Anyway, I wanted to keep my tests clean in the future, so I added a registration step for mocks. Here's a simplified version:

defcleanUpMocks(self):fork,vinself.mocks.items():forcallingetattr(v,'_registered',[]):ifnotgetattr(v,call).called:raiseMockError('{0}.{1} registered but not called.'.format(self.registered_mocks[k].__name__,call))

In this example: create is in the list of _registered on the Mock. When the test completes we check it got called. If you run that test without anything else, it will fail because the mock never actually got called.

If what is passed to the mock is important, all the usual methods like assertcalledwith can be called.