Mock is a way to replace parts of your system in order to test your unit
independently of the other one. Mocks can be see like an object that allow any
method, attribute to be called/accessed. The behavior can - of course - be
defined if you want a specific response to a given method.
Note that for a specific element (for example a method) the same mock is always
Last but not least mock record every call which allow you to check that
expected calls are made.
The goal of a unit test is to test if execution result is as expected, it
should not test the implementation details. In other word implementation may
change, unit test should still pass.
Here the test is really low level to cover a wide range of mock usage
with a minimal code base, but depending of your testing strategy, your test
can “zoom” less in the interaction details.
This test case will try to show you a quick overview of how mock can be in
order to test a class. I have tried to cover the most common case but
there is still many things. See
python mock documentation
for more details.
In this example test case I assume that you understand how unit test are
written in python: test case classes, make assertion and how to run it (nose,
pytest, …). If it is not the case, you may find more informations on
official python documentation.
Materials & method
This blog post will be written as a commented python test case to help you
understand clearly interactions between code and tests.
Code was written for python 2.7 and file organization is the follow:
Dependencies (can be installed using pip in a
virtualenv of course):
To be test code
Here is a simple queue wrapper (queue.py)to ease the use of
Let’s write some tests!
This example show you a quick overview of mock’s most common features, but there
is many more!
To really master mock it takes some time and practice. Just give it a try on
your next project, you will gain some skills, your project will be more robust
and your user more happy with fewer bugs!
To finish a good news for python 3.3+ users, mock have been added to standard
library, you can directly import it from