Pytest Mocking Tutorial: Patch Dependencies Without Hiding Bugs
Test a wallet with a controlled exchange rate, simulate lookup failures, and see how stricter mocks catch calls that real code would reject.
Article summary
TL;DR
- Mocking lets a test choose what a dependency returns or which error it raises, while your own code still runs.
- Use pytest-mock to replace a dependency temporarily and check how your code uses it.
- Mocks can accept calls that real code would reject. Interface checks help catch those mistakes.
Code for this article
Open the repository to follow along.
artem-istranin/istranin-dev-code-examples01 / MOCKING BASICS
Test your code with a dependency you can control.
Suppose a wallet converts dollar deposits into euros. In a larger application, a background job could fetch exchange rates from a 3rd-party API and save them in a database. The wallet’s rate provider would read the latest stored rate.
Now try testing a 100 USD deposit. At a rate of 0.90 EUR per USD, the balance should become 90 EUR. After a rate update to 0.92, the same code produces 92 EUR. A test that always expects 90 EUR could fail because the data changed, even if the wallet’s calculation is correct.
The test needs to choose the rate. Mocking lets us replace the rate lookup with a substitute that always returns 0.90 for this test. The wallet’s actual calculation still runs, so we can expect 90 EUR every time.

The blue connections show the test taking over the wallet’s inputs and checking its output. The gray dependency path is skipped, so changing stored rates cannot affect this test.
For the runnable tutorial, a local JSON file stands in for the database. No API credentials or database server are needed. We’ll keep the same boundary: run the real wallet and replace its rate lookup. Then we’ll simulate a failed lookup and check that the wallet keeps its existing balance.
What is mocking in pytest?
Mocking replaces a dependency with a controllable substitute during a test. A dependency is something your code calls or reads, such as another object, a file, or an API. The substitute can return a chosen value, raise an error, and record how your code used it.
Patching is how we temporarily put that substitute in place. In this tutorial, we’ll use the pytest-mock plugin to manage those replacements.
Decide which behavior stays real
Our test keeps the wallet’s balance calculation real and replaces its rate lookup. Replacing the balance calculation itself would skip the behavior we want to check.
Mocks also have a limit: a replacement can behave differently from the real dependency. We’ll explore this problem, called mock drift, later and use interface checks to catch incorrect method calls.
02 / THE MOCKER FIXTURE
Run the wallet example, then replace its rate lookup.
A pytest fixture supplies a test with something it needs. If you’re new to pytest, start with the beginner’s guide to writing and running tests.
The pytest-mock plugin provides a fixture named mocker, which creates replacements and restores patched objects after the test. Add mocker to the test function’s parameters to request it; you don’t import a variable named mocker.
The linked companion repository contains the finished code and all 16 tests. Follow along by reading and running those files; most snippets below explain them, so you do not need to paste duplicate tests into the checkout. The mock-drift section will explicitly ask you to create and remove a temporary test. You will need Git and uv, which manages the example’s Python environment and dependencies. Run:
git clone https://github.com/artem-istranin/istranin-dev-code-examples.git
cd istranin-dev-code-examples/pytest-mocking-tutorial
uv sync --locked
uv run pytest
Expect 16 passed; the timing will vary. The project uses Python 3.13 or newer, with pytest 9.1.1 and pytest-mock 3.15.1 pinned in its lockfile. Run the remaining commands from this example directory. In your own existing uv project, uv add --dev pytest pytest-mock adds the testing tools instead.
For more practice choosing what to mock and writing useful assertions, follow the Pytest course. Start with the free lessons.
View courseThe example has 2 main parts:
wallet/main.pycontainsWallet, which maintains a balance in euros.wallet/fx.pycontainsRateProvider, which reads exchange rates from a JSON file.get_rate("USD", base="EUR")returns the multiplier for converting dollars into euros.
The JSON file plays the database’s role from the diagram. A sample file contains {"USD/EUR": "0.90"}; these are illustrative values, not current exchange rates.
Here is the wallet’s main behavior:
# wallet/main.py
from decimal import Decimal
from pathlib import Path
from wallet.fx import RateProvider
class Wallet:
def __init__(self, rates_path: Path):
self.rates = RateProvider(rates_path)
self._balance = Decimal("0")
def add(self, amount: Decimal, currency: str) -> None:
rate = (
Decimal("1")
if currency == "EUR"
else self.rates.get_rate(currency, base="EUR")
)
self._balance += amount * rate
def balance(self) -> Decimal:
return self._balance
Decimal represents decimal amounts without the binary floating-point surprises of values such as 0.1. We construct it from strings. This small example expects uppercase currency codes and leaves production concerns such as rounding policies and transaction storage out of scope.
Replace the lookup and check the balance
For the first test, replace only the provider’s rate lookup:
# tests/test_wallet.py
from decimal import Decimal
from wallet.fx import RateProvider
from wallet.main import Wallet
def test_add_dollars_with_patched_method(mocker, tmp_path):
get_rate = mocker.patch.object(
RateProvider, "get_rate", return_value=Decimal("0.90")
)
wallet = Wallet(tmp_path / "unused.json")
wallet.add(Decimal("100"), "USD")
assert wallet.balance() == Decimal("90")
get_rate.assert_called_once_with("USD", base="EUR")
mocker.patch.object takes an object and the name of an attribute to replace. Here, it replaces RateProvider.get_rate. return_value is the value the replacement returns when called, so the test supplies a known rate of 0.90.
tmp_path is pytest’s fixture for a temporary directory unique to the test. No file is created here. The real provider’s constructor only remembers the path, and the patched method never reads it.
The balance assertion checks the wallet’s result. The call assertion checks a meaningful detail at the dependency boundary: it requested the USD-to-EUR rate exactly once. Avoid asserting every internal helper call just because a mock can record them.
Run this first example on its own:
uv run pytest tests/test_wallet.py::test_add_dollars_with_patched_method
Expect 1 passed. To see that the assertion checks the real calculation, temporarily change this test’s expected balance from Decimal("90") to Decimal("91"). Run the same command: it should report 1 failed. Restore Decimal("90") and rerun to get 1 passed again.
If pytest reports fixture 'mocker' not found, check that pytest-mock is installed in the environment running the tests. In this project, uv sync --locked installs it and uv run pytest uses that environment.
The replacement makes the rate predictable while the wallet still multiplies the deposit by it. Next, we’ll change the mock’s behavior to check failed lookups too.
Do you need pytest-mock to mock dependencies in pytest?
No. Python’s standard-library unittest.mock works in pytest tests without a plugin. pytest-mock adds the mocker fixture to manage patches and provide pytest-friendly assertions. Pytest also includes monkeypatch, which temporarily replaces attributes, dictionary values, or environment variables.
| Tool | Use it when |
|---|---|
mocker from pytest-mock |
You want configurable mock objects and call assertions with fixture-managed cleanup. |
unittest.mock |
You want the same core mock tools without the plugin, using a context manager or decorator to manage a patch. |
monkeypatch from pytest |
You want to set an environment variable or substitute a function or value you provide yourself. It does not add mock call recording by itself. |
We’ll use mocker for the wallet tests. See pytest’s monkeypatch guide when a simple replacement or environment setting is all you need.
03 / CLASSES AND FAILURES
Replace a class and control its instance.
The first test still constructs a real RateProvider; only its lookup method is replaced. Our constructor is cheap, but another provider might open a connection or load data during construction.
How do you mock a Python class with pytest-mock?
Use mocker.patch to replace the class name used by the calling code before creating the object under test. Configure the class mock’s return_value to control the instance that the constructor call returns.
The following test belongs in tests/test_wallet.py and reuses its existing imports. This first version leaves out the interface checks we’ll add next; the companion contains the final version:
def test_add_dollars_with_patched_class(mocker, tmp_path):
provider_class = mocker.patch("wallet.main.RateProvider")
provider = provider_class.return_value
provider.get_rate.return_value = Decimal("0.90")
wallet = Wallet(tmp_path / "unused.json")
wallet.add(Decimal("100"), "USD")
assert wallet.balance() == Decimal("90")
provider.get_rate.assert_called_once_with("USD", base="EUR")
mocker.patch takes a dotted target string. In wallet/main.py above, Wallet.__init__ calls the imported name RateProvider, so we patch wallet.main.RateProvider.
There are 2 different calls to configure. The wallet first calls RateProvider(rates_path) to obtain a provider object. It then calls that object’s get_rate(...) method. The class mock creates a mock return value automatically. Calling the patched class returns that same object, so we configure its get_rate method before creating the wallet.
| Configuration | What it controls |
|---|---|
provider_class.return_value |
The object returned when the patched class is called |
provider.get_rate.return_value |
The rate returned when that object’s method is called |
Setting provider_class.get_rate.return_value would configure a method on the class mock, not on the instance the wallet receives.
By default, patching an ordinary class creates a MagicMock. Like Mock, it records calls and lets you configure results; it also supports Python protocols through special methods, such as those used by context managers. You don’t need to construct either directly for this example.
How do you make a mock raise an exception in pytest?
Set the mock’s side_effect to an exception to make it raise that error when called. Set return_value when the call should return normally.
Our real provider raises RateUnavailable when it cannot supply a usable rate. The wallet should let that exception reach its caller and preserve the balance it already had. side_effect lets the test trigger this situation deliberately:
import pytest
from wallet.fx import RateUnavailable
def test_missing_rate_leaves_existing_balance_unchanged(mocker, tmp_path):
provider_class = mocker.patch("wallet.main.RateProvider")
provider_class.return_value.get_rate.side_effect = RateUnavailable("Offline")
wallet = Wallet(tmp_path / "unused.json")
wallet.add(Decimal("20"), "EUR")
with pytest.raises(RateUnavailable, match="Offline"):
wallet.add(Decimal("100"), "USD")
assert wallet.balance() == Decimal("20")
Adding euros requires no lookup, so the initial deposit succeeds. The dollar deposit then triggers the configured exception. pytest.raises checks that it occurs, and the final assertion checks that the failure didn’t corrupt the balance.
Besides exceptions, side_effect accepts a callable or a sequence of results. Those are useful for input-dependent responses or retries, but a fixed return value or 1 exception is usually the clearest starting point.
04 / MOCK DRIFT
Catch mocks that accept invalid calls.
Mock drift happens when a test’s replacement no longer matches the dependency it represents. Let’s introduce an incorrect method call and see how a mock can hide it.
Create a temporary file, tests/test_mock_drift_demo.py, with this test:
from decimal import Decimal
from wallet.main import Wallet
def test_dollar_deposit(mocker, tmp_path):
provider_class = mocker.patch("wallet.main.RateProvider")
provider = provider_class.return_value
provider.get_rate.return_value = Decimal("0.90")
wallet = Wallet(tmp_path / "unused.json")
wallet.add(Decimal("100"), "USD")
assert wallet.balance() == Decimal("90")
This deliberately checks only the balance. It leaves out the earlier call assertion and the interface checks already present in the companion’s finished class-based tests. Run this temporary test on its own:
uv run pytest tests/test_mock_drift_demo.py
You should see 1 passed: the wallet converts 100 USD into 90 EUR using the rate we supplied.
Now inspect the real method in wallet/fx.py:
def get_rate(self, currency: str, *, base: str) -> Decimal:
The * makes base a keyword-only argument. The wallet correctly calls it with base="EUR". In wallet/main.py, temporarily change that call inside Wallet.add to use the wrong argument name:
self.rates.get_rate(currency, target="EUR")
Leave the provider’s signature unchanged. Run the temporary test again:
uv run pytest tests/test_mock_drift_demo.py
It still reports 1 passed. The real method has no target parameter, but our unrestricted mock accepts the call and returns Decimal("0.90"). The balance is correct only because the replacement lets an invalid call through. That is the gap we need to close.
Our earlier assert_called_once_with("USD", base="EUR") would catch this particular mistake. Next, we’ll make the mock check the method’s interface even when the test asserts only the balance.
What do autospec and spec_set check in Python mocks?
autospec=True makes a mock follow the real object’s available attributes and call signatures. spec_set=True also rejects assigning attributes that are not in that specification. These checks catch interface mistakes in both the code under test and the mock’s setup.
Keep the incorrect target="EUR" call for now. In tests/test_mock_drift_demo.py, replace the patch line with:
provider_class = mocker.patch(
"wallet.main.RateProvider", autospec=True, spec_set=True
)
Keep the rest of the test unchanged and rerun:
uv run pytest tests/test_mock_drift_demo.py
Now you should see 1 failed. With the example’s Python 3.13 environment, the traceback includes:
TypeError: missing a required keyword-only argument: 'base'
The failure happens when the wallet calls get_rate, before it reaches the balance assertion. autospec copied the real method’s signature, so passing target no longer satisfies its required base parameter.
Restore the correct call in wallet/main.py:
self.rates.get_rate(currency, base="EUR")
Run the same command again. Expect 1 passed, with the interface checks still enabled.
To see what spec_set adds, temporarily insert this line immediately after provider = provider_class.return_value in the test:
provider.get_rates = mocker.Mock()
The plural get_rates is a typo: RateProvider defines get_rate. Rerun the temporary test. It fails while configuring the mock with:
AttributeError: Mock object has no attribute 'get_rates'
spec_set caught the attempt to assign a nonexistent attribute. Remove that line and rerun to get 1 passed again.
The companion’s 2 class-based wallet tests already use autospec=True, spec_set=True. Delete the temporary tests/test_mock_drift_demo.py file, then run uv run pytest. With the valid base="EUR" call restored, all 16 tests should pass.
This is autospec=True, not pytest’s autouse=True. The latter makes a fixture run without being named as a test parameter; it does not validate mocks.
Does autospec validate a mock’s return value?
No. Autospeccing checks names and call signatures, but it doesn’t check whether a configured return value is correct or enforce return type annotations. You can still configure the wrong exchange rate, misunderstand which currency a rate refers to, or return data that a real service never produces.
There is also a practical limit when autospeccing classes: attributes created only inside __init__ may not be visible in the class specification. Our tests configure get_rate, a method defined on the class, so they don’t need the instance’s path attribute. See Python’s autospeccing documentation when applying this to more complex objects.
Keep the object’s main responsibility real
The wallet owns conversion and balance updates, so those stay real in its tests. Mocking the rate lookup lets us arrange a chosen rate or failure. For RateProvider, reading and interpreting rates is the responsibility itself; its tests need to exercise that code with a real file.
Apply the same judgment to assertions. Checking which currency pair the wallet requests protects a meaningful interaction. Checking every internal helper call would make harmless refactoring break tests. Running every dependency in every test can also make failures harder to locate. Choose enough of the system to verify the use case clearly.
Keep the object’s main responsibility real. Mock dependencies only when that helps you test a use case.
We’ve controlled a rate, simulated a lookup failure, and caught an invalid method call. For tests that use real components together, continue with the guide to unit and integration testing.
Build on this example with fixtures, parametrization, mocking, and API tests in the Pytest course. Explore the lessons and practice on real Python code.
View courseMore field notes
Keep reading.
Unit Testing vs Integration Testing vs E2E: Python Examples
Follow one Python converter through unit, integration, and end-to-end tests. Break its calculation, configuration, and output to see why each boundary matters.
Python testingpytestPytest Fixtures and Parametrization Best Practices
Reuse pytest setup without hiding what each test checks. Follow an inventory example through fixtures, parameter tables, failures, and fresh test data.
pytestPython testingPython Unit Testing Best Practices: 10 pytest Rules
Write Python unit tests that survive refactoring. Use pytest to protect behavior, choose useful cases, control dependencies, and keep the suite fast.
Python unit testingpytest