Python Pytest Mock: Functions, Classes, Return Values, Side Effects
Learn to mock functions and classes in Python pytest with unittest.mock: set return values, define side effects, patch classes, verify calls, and test async code.

Mocking in pytest means replacing a dependency with a controllable stand-in from the standard library’s unittest.mock module. This lets you decide what a function returns, what exception it raises, and how it was called, without relying on external services or databases.
This guide covers the practical patterns for mocking functions and classes in pytest, setting return_value and side_effect, verifying call behavior, and mocking async functions.
Why Mocking Is Central to pytest Tests
Mocking isolates the unit under test from its dependencies. For example, you can test a function that calls an external API without making a network request, or test a database-backed method without a live database. Mocks also make tests deterministic by removing timing and environment-dependent failures.
In addition to controlling behavior, mocks let you verify interactions. You can assert that a function was called with specific arguments, that it was called a certain number of times, or that it raised an expected exception.
Mocking a Function with return_value
The simplest pattern is to replace a function with a mock that returns a fixed value. Use unittest.mock.patch as a context manager or decorator.
Suppose myapp.py imports the real get_user function from an external service:
# myapp.py
from external_service import get_user
def fetch_user_name():
user = get_user(1)
return user["name"]To test fetch_user_name without calling the external service, patch the name in myapp’s namespace:
from unittest.mock import patch
from myapp import fetch_user_name
def test_fetch_user_name():
with patch("myapp.get_user") as mock_get_user:
mock_get_user.return_value = {"name": "Alice"}
assert fetch_user_name() == "Alice"
mock_get_user.assert_called_once_with(1)The return_value attribute controls what the mock returns when called. You can also set it after creating a mock instance directly.
If you need the mock to return different values on successive calls, use side_effect with a list.
Controlling Behavior with side_effect
side_effect is more flexible than return_value. It can be:
- A callable that computes the return value from the arguments.
- An exception class or instance to raise.
- A list of values to return in sequence.
Raising Exceptions
import pytest
from unittest.mock import patch
from myapp import fetch_user_name
def test_get_user_raises():
with patch("myapp.get_user") as mock_get_user:
mock_get_user.side_effect = KeyError("missing")
with pytest.raises(KeyError):
fetch_user_name()Returning a Sequence
def test_sequence():
with patch("myapp.get_user") as mock_get_user:
mock_get_user.side_effect = [{"name": "Alice"}, {"name": "Bob"}]
assert fetch_user_name() == "Alice"
assert fetch_user_name() == "Bob"When side_effect is a list, each call consumes the next value. If the list is exhausted, a StopIteration is raised.
Using a Callable
def test_dynamic_return(mocker):
mock_get_user = mocker.patch("myapp.get_user")
mock_get_user.side_effect = lambda user_id: {"name": f"User{user_id}"}
assert fetch_user_name() == "User1"This lets you compute the return value from the call arguments.
Mocking Classes and Their Instances
Mocking a class is different from mocking a function. When you patch a class, you replace the class object itself. Calling the mock class returns a new mock instance.
Suppose your application code creates a Database object and calls a method on it:
# myapp.py
class Database:
def query(self, sql):
...
def get_data():
db = Database()
return db.query("SELECT * FROM users")To mock Database:
from unittest.mock import patch
from myapp import get_data
def test_get_data():
with patch("myapp.Database") as MockDatabase:
instance = MockDatabase.return_value
instance.query.return_value = [{"id": 1}]
assert get_data() == [{"id": 1}]MockDatabase.return_value is the mock instance that Database() returns when the patched class is called. You can set its methods’ return values or side effects as needed.
You can also patch instance methods directly if you already have an object.
Choosing Between Mock and MagicMock
Mock and MagicMock are both from unittest.mock. The difference is that MagicMock pre-configures magic methods like __len__, __iter__, and __getitem__ to work by default. This is useful when your code uses those protocols.
| Feature | Mock | MagicMock |
|---|---|---|
| Magic methods | Not configured by default | Pre-configured |
| Best for | Simple function stubs and isolated class fakes | Objects that use protocols such as __len__, __iter__, or __getitem__ |
For most mocking in pytest, MagicMock is a safer default because it behaves more like a real object. If you only need to stub a function call, Mock is sufficient.
Common Pitfalls When Patching
Patching the Wrong Location
You must patch where the name is looked up, not where it is defined. If myapp imports get_user from another module, patch "myapp.get_user", not "othermodule.get_user".
Forgetting to Set return_value
If you don't set return_value, the mock returns another mock. That can cause confusing behavior when your code expects a real value.
Overusing Mocks
Mocking too much can hide integration issues. Use mocks for external boundaries, but let internal logic run naturally.
Not Asserting Calls
Without call assertions, a passing test only shows that the code ran. Use assert_called_once, assert_called_with, and call_count to verify interactions.
Using pytest-mock for Cleaner Fixtures
The pytest-mock plugin provides a mocker fixture that wraps unittest.mock. It automatically undoes patches after each test, reducing boilerplate.
def test_get_user(mocker):
mock_get_user = mocker.patch("myapp.get_user")
mock_get_user.return_value = {"name": "Alice"}
assert fetch_user_name() == "Alice"
mock_get_user.assert_called_once_with(1)The mocker fixture also provides mocker.spy for wrapping existing functions and other utilities. It is the recommended way to mock in pytest because it integrates with the fixture lifecycle.
Verifying Calls and Call Counts
Mocking is not only about return values. You often need to verify that a function was called with specific arguments or called a certain number of times. Common assertion methods on a mock include:
mock_get_user.assert_called_once()verifies exactly one call was made.mock_get_user.assert_called_with(1)verifies the most recent call received1.mock_get_user.assert_any_call(2)verifies at least one call received2.assert mock_get_user.call_count == 3checks the total number of calls.
You can also inspect call_args_list to see the full history of calls. When you need to verify a sequence of calls, use assert_has_calls with call objects.
from unittest.mock import call
mock_get_user.assert_has_calls([call(1), call(2)])This example asserts that calls with 1 and 2 occurred in that order.
Mocking Asynchronous Functions
If your code uses async functions, use AsyncMock from unittest.mock (available in Python 3.8+).
from unittest.mock import AsyncMock
async def fetch_data():
return await api_call()
async def test_fetch_data(mocker):
mock_api = mocker.patch("myapp.api_call", new=AsyncMock())
mock_api.return_value = {"data": 42}
assert await fetch_data() == {"data": 42}AsyncMock supports await and provides the same call assertion methods as regular mocks, plus assert_awaited and related methods for awaitable behavior.
If you write async test functions, run them with an async pytest plugin such as pytest-asyncio, or call the coroutine with asyncio.run() inside a regular test.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.