Mastering Python Mock and Patch: Mocking For Unit Testing

Claudio Sabato
9 min readMar 5

Have you heard about Python mock and patch as a way to improve your unit tests? You will learn how to use them in this tutorial.

Unit tests are key to software development because they ensure that your code works as planned.

Python has many robust tools for writing and running unit tests in a controlled environment by creating mocks. The Mock class is part of the unittest.mock library and it allows to create mock objects. The patch function, in the same library, allows replacing real objects with mocks.

Let’s learn about Python mocks!

Which Module Do you Use for Mocking in Python?

Mocking is a technique used in unit testing to replace parts of code that cannot be easily tested with mock objects that replicate the behavior of real objects.

The Python unittest.mock library provides a framework for building and manipulating mock objects in unit tests.

Mock objects help create a controlled test environment. They simulate the behavior of real objects, but with inputs and outputs that you can control. This allows you to isolate and test code that otherwise would be very hard to test due to external dependencies.

You can use the mock class and the patch function by importing the unittest module.

import unittest

How Do You Create a Mock using the Python Mock Class?

To create mock objects, you can use the Mock class part of the unittest module.

>>> from unittest.mock import Mock
>>> Mock
<class 'unittest.mock.Mock'>

From unittest.mock we have imported the Mock class. Now we can create a Mock object.

>>> mock = Mock()
>>> mock
<Mock id='140397919063152'>

The purpose of a Mock is to replace a real Python object but to do that the mock has to provide the same methods and attributes as the real object.

So, how do Python mocks handle this?

Let’s try to get the value of an attribute of the mock we have created or call a method of the mock:

Claudio Sabato

I’m a Software Engineer and Programming Coach. I want to help you in your journey to become a Super Developer!