Mock

In this chapter, we will test the CLI. To do this, we will use the mock library, which has been included as part of the standard Python library since Python 3.3 under the name unittest.mock.

Objects that are not real can be either dummies, fakes, stubs, mocks or spies. They are all what are known as test doubles. However, with pytest’s own monkeypatch fixture and unittest.mock, you should have all the functionality you need.

The three core functionalities of unittest.mock are:

Mock

The Mock class can be used to simulate any object.

MagickMock

A subclass of Mock that contains all magic methods, such as __str__, __len__, etc.

patch-Methode

An object is searched for within a specific module and replaced with another object.

In the following, we will look at mocking return values, checking calls to mock functions, and mocking exceptions. However, there are a whole range of other mocking techniques that we will not cover. So be sure to read unittest.mock — mock object library if you wish to make extensive use of mocking.