Mocking in Python with unittest.mock
allows you to simulate complex logic or unpredictable dependencies, such as responses from external services. You create mock objects to replace real ones in your tests, ensuring that your tests are isolated. The Mock
class allows you to imitate real objects, and the patch()
function lets you temporarily substitute mocks for real objects in your tests.
By the end of this tutorial, you’ll understand that:
- A mock in Python is a substitute object that simulates a real object in a testing environment.
Mock
differs fromMagicMock
in thatMagicMock
includes implementations of most magic methods.- The
patch()
function replaces real objects with mock instances, controlling the scope of mocking. - You can assert if a
Mock
object was called with methods like.assert_called()
. - You set a mock’s return value by assigning a value to the mock’s
.return_value
attribute.
In this tutorial, you’ll explore how mocking enhances your testing strategy by enabling controlled and predictable test environments for your Python code. When you can control the behavior of your code during testing, you can reliably test that your application logic is correct.
Get Your Code:Click here to download the free sample code that you’ll use to learn about Python’s mock object library.
Take the Quiz: Test your knowledge with our interactive “Understanding the Python Mock Object Library” quiz. You’ll receive a score upon completion to help you track your learning progress:
Interactive Quiz
Understanding the Python Mock Object LibraryIn this quiz, you'll test your understanding of Python's unittest.mock library. With this knowledge, you'll be able to write robust tests, create mock objects, and ensure your code is reliable and efficient.
What Is Mocking?
A mock object substitutes and imitates a real object within a testing environment. Using mock objects is a versatile and powerful way to improve the quality of your tests. This is because by using Python mock objects, you can control your code’s behavior during testing.
For example, if your code makes HTTP requests to external services, then your tests execute predictably only so far as the services are behaving as you expected. Sometimes, a temporary change in the behavior of these external services can cause intermittent failures within your test suite.
Because of this, it would be better for you to test your code in a controlled environment. Replacing the actual request with a mock object would allow you to simulate external service outages and successful responses in a predictable way.
Sometimes, it’s difficult to test certain areas of your codebase. Such areas include except
blocks and if
statements that are hard to satisfy. Using Python mock objects can help you control the execution path of your code to reach these areas and improve your code coverage.
Another reason to use mock objects is to better understand how you’re using their real counterparts in your code. A Python mock object contains data about its usage that you can inspect, such as:
- If you called a method
- How you called the method
- How often you called the method
Understanding what a mock object does is the first step to learning how to use one. Next, you’ll explore the Python mock object library to see how to use Python mock objects.
The Python Mock Library
Python’s built-in mock object library is unittest.mock
. It provides an easy way to introduce mocks into your tests.
Note: The standard library includes unittest.mock
starting from Python 3.3 and in all newer versions. If you’re using an older version of Python, then you’ll need to install the official backport of the library.
To do so, install mock
from the Python Package Index (PyPI) using pip
:
$ python-mpipinstallmock
You may want to create and activate a virtual environment before installing the package.
unittest.mock
provides a class called Mock
, which you’ll use to imitate real objects in your codebase. Mock
, along with its subclasses, offers incredible flexibility and insightful data that will meet most of your Python mocking needs.
The library also provides a function called patch()
, which replaces the real objects in your code with Mock
instances. You can use patch()
as either a decorator or a context manager, giving you control over the scope in which the object will be mocked. Once the designated scope exits, patch()
will clean up your code by replacing the mocked objects with their original counterparts.
Finally, unittest.mock
provides solutions for some of the issues inherent in mocking objects, which you’ll explore later in this tutorial.
Now that you have a better understanding of what mocking is and the library you’ll be using, it’s time to dive in and explore the features and functionalities unittest.mock
has to offer.
The Mock
Object
unittest.mock
offers a base class for mocking objects called Mock
. The use cases for Mock
are practically limitless because Mock
is so flexible.
Begin by instantiating a new Mock
instance:
>>> fromunittest.mockimportMock>>> mock=Mock()>>> mock<Mock id='4561344720'>
Read the full article at https://realpython.com/python-mock-library/ »
[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]