Mocking and Patching
Learn the basics of mocking and patching using pytest.
Introduction to mocking and patching
Mocking and patching are crucial techniques in software testing that allow the replacement of parts of a system with fake objects called mocks. This technique simulates behavior and data, which enables testing specific parts of a system without relying on other parts. As a result, this technique can help isolate and identify issues in the code.
Difference between mocking and patching
Mocking creates a fake object that mimics the behavior of a real object. The purpose is to isolate the code under test from external dependencies, such as databases or web services. By replacing external dependencies with fake objects, the code can be tested in isolation without the need for a real environment. It’s mainly used for unit testing, where a single function or method is tested.
Patching, on the other hand, involves replacing the implementation of a function or method with a mock object. The purpose is to modify the behavior of a function or method that’s called by the code under test. It’s mainly used for integration testing, where the interactions between multiple components of a system are tested.
To sum up, mocking isolates the code under test from external dependencies, while patching modifies the behavior of functions or methods that are called by the code under test.
Patching using monkeypatch
Pytest provides a monkeypatch
fixture that helps safely modify attributes, dictionary items, environment variables, or sys.path
for importing in tests. It provides methods like setattr()
, delattr()
, setitem()
, delitem()
, setenv()
, delenv()
, syspath_prepend()
, and chdir()
to modify the behavior of functions, properties of a class, dictionaries, environment variables, and current working directories for a test.
The changes made using monkeypatch
are undone after the test. It can be used to patch a function with a desired behavior, modify global configurations, test program behavior with missing environment variables, modify the $PATH
variable, and modify sys.path
for namespace packages and module imports.
Let’s take a look at an example:
Create a free account to view this lesson.
By signing up, you agree to Educative's Terms of Service and Privacy Policy