To mock dependencies with unittest.mock in pytest, replace the external thing your code calls, such as an HTTP client, a database or the clock, with a Mock or MagicMock object, then assert how it was called. The standard tool is unittest.mock.patch, which swaps a name for a mock during one test. This gives you fast, deterministic tests for code that talks to the outside world, and the same approach with python unittest mock pytest works in plain functions without any TestCase class.
This guide uses the standard library unittest.mock on Python 3.13 with pytest 8. No extra package is required.
A mock is a stand-in object that records how it is used and returns values you choose. You mock a dependency when using the real one would be slow, costly, random or unavailable: a payment API, the network, the current time.
Mock the boundary of your system, not your own logic. If you mock everything, the test only proves that the mocks agree with each other.
Here is the code under test:
Mock creates attributes and methods on demand. MagicMock also supports magic methods such as __len__ and __enter__, so it is the default choice.
Set return_value for a fixed answer, or side_effect for a sequence, a function or an exception:
The first two calls return 1 and 2, and the third raises the error. The most useful assertions are assert_called_once_with, assert_not_called, call_count and call_args.
patch swaps an attribute for a MagicMock while the test runs, then restores it. The most common mistake is patching the wrong place: patch the name where it is looked up, which is where your code uses it.
patch also works as a decorator, in which case the mock is added as an argument:
When stacking several decorators, the bottom one provides the first argument. Because from x import y copies the name, patch "mymodule.y" and not "x.y" in that case.
A plain MagicMock accepts any call, so a typo in your test or a changed signature goes unnoticed. Use autospec=True or create_autospec so the mock has the same signature and attributes as the real object:
Prefer autospec for anything you control, since it keeps mocks honest as the real code changes.
Wrapping patch in a fixture lets many tests share it and keeps tests short:
Use patch.object(obj, "name") when you already hold the object, and patch.dict(os.environ, {"KEY": "value"}) for dictionaries. For simple replacement with no call tracking, pytest's own monkeypatch fixture may be enough. The pytest-mock plugin offers a mocker fixture that wraps the same API if you prefer less boilerplate.
Since Python 3.8, AsyncMock handles coroutines, and patch picks it automatically when the target is an async def function.
MagicMock supports with blocks out of the box, so mocking a file or lock used as a context manager also works.
| Mistake | Better approach |
|---|---|
| Patching where the object is defined, not where it is used | Patch the name in the module under test |
| Asserting on every internal call | Assert on behaviour and key outputs |
| Mocking your own pure functions | Call the real ones |
| A mock with no spec that hides typos | Use autospec=True |
| Forgetting that a mock is truthy and accepts anything | Set explicit return values |
Misspelt assertion like assert_called_once_wiht | Use autospec, which raises on unknown attributes in modern Python |
MagicMock is a Mock with default implementations of magic methods, so it works with len, iteration, indexing and with. Use it by default.
You most likely patched the original module rather than the name your code imports. Patch the path where the code under test looks the name up.
Both give the same objects. pytest-mock adds a mocker fixture that undoes patches automatically, which some teams find tidier.
Set side_effect to an exception class or instance, and the mock raises it when called.
Mock only the outside boundary of your code: set return_value or side_effect, then check calls with assert_called_once_with and related methods. Use patch on the name as it is looked up in the module under test, add autospec=True to keep mocks faithful, wrap patches in fixtures for reuse, and use AsyncMock for coroutines.