Spying on instance methods with Python's mock module

** Thu 29 October 2015

Python’s mock module (unittest.mock in Python 3.3 and higher) allows you to observe parameters passed to functions.

I’m a little slow, so I had to dig around to figure out how to do this.

Let’s say you have a class:

Now, let’s suppose you are testing the functionality of ProductionClass, but you want to observe the parameters passed to your internal methods but still invoke those internal methods. I didn’t find a lot of examples of this from my Google searches, so here is the solution using unittest.mock (or mock from PyPI if you’re on Legacy Python 2.x):

Happy hunting.