Back To Blog Posts
Mocking Module Level Functions In Python Unit Tests
If you write a lot of unit tests in python, especially on complex pieces of software, no doubt you have come across python’s mock module. As of writing this, I just noticed that it has now been pulled into the python standard library unittest module
It is easy to use mock to mock class-level instance methods:
And now in some unit test
That was easy enough, but mocking module level functions is actually not as easy. Lets say I have some module called name_utis.py
that’s sole job is to concatenate first name and last name:
And lets say this function is called by some other class:
My goal is to mock make_whole_name
, not get_name
. This can be done by using the following