Using Mock Objects
Learn about the different types of mock objects and how to create test doubles.
We'll cover the following
In unit testing terminology, there are several types of object that fall into the category named test doubles. A test double is a type of object that will take the place of a real one in our test suite for different kinds of reasons (maybe we don't need the actual production code, but a dummy object will work, or maybe we can't use it because it requires access to services or it has side effects that we don't want in our unit tests, and so on).
There are different types of test double, such as dummy objects, stubs, spies, or mocks.
Mocks are the most general type of object, and since they're quite flexible and versatile, they are appropriate for all cases without needing to go into much detail about the rest of them. It is for this reason that the standard library also includes an object of this kind, and it is common in most Python programs. The one we are going to be using here is unittest.mock.Mock
.
A mock is a type of object created to a specification (usually resembling the object of a production class) and some configured responses (that is, we can tell the mock what it should return upon certain calls, and what its behavior should be). The Mock
object will then record, as part of its internal status, how it was called (with what parameters, how many times, and so on), and we can use that information to verify the behavior of our application at a later stage.
In the case of Python, the Mock
object that's available from the standard library provides a nice API to make all sorts of behavioral assertions, such as checking how many times the mock was called, with what parameters, and so on.
Types of mocks
The standard library provides Mock
and MagicMock
objects in the unittest.mock
module. The former is a test double that can be configured to return any value and will keep track of the calls that were made to it. The latter does the same, but it also supports magic methods. This means that, if we have written idiomatic code that uses magic methods (and parts of the code we are testing will rely on that), it's likely that we will have to use a MagicMock
instance instead of just a Mock
.
Trying to use Mock
when our code needs to call magic methods will result in an error. See the following code for an example of this:
Get hands-on with 1400+ tech skills courses.