Member-only story

A Quick Guide to Python Mocking and Patching

Elshad Karimov
2 min readSep 3, 2024
Photo by Muhammad Asyfaul on Unsplash

Mocking and patching are powerful techniques in Python that allow developers to test their code by simulating different parts of the system. This is especially useful for isolating parts of your code that have external dependencies, such as databases, APIs, or files.

What is Mocking?

Mocking involves creating a “mock” version of an object, function, or method that behaves like the real one but without executing any real logic. This allows you to control the behavior of these objects in a test environment, making it easier to test how your code handles different scenarios.

The unittest.mock module provides tools for creating mocks and setting their behavior:

from unittest.mock import Mock

# Create a mock object
mock = Mock()

# Set return value of the mock method
mock.some_method.return_value = "Hello, Mock!"

# Use the mock in place of a real object
print(mock.some_method()) # Output: Hello, Mock!

What is Patching?

Patching temporarily replaces an object or function with a mock object for the duration of a test. This is useful for replacing external dependencies or isolating parts of your code that you don’t want to execute during testing.

--

--

Elshad Karimov
Elshad Karimov

Written by Elshad Karimov

Software Engineer, Udemy Instructor and Book Author, Founder at AppMillers

No responses yet