Python mocking and test doubles: stubs, fakes, unittest.mock
11 steps · about 3 h 46 min · Intermediate
- Stub vs Mock vs Spy vs Fake: Test Doubles Explained (article, QASkills, 15 min)
A side-by-side table of the five kinds of test double gives you the vocabulary before any Python API.
- Mocks Aren't Stubs (article, Martin Fowler, 40 min)
The original essay on state versus behaviour verification explains why the terms matter and when mocks make tests fragile.
- Test Doubles in Python unit tests (article, Szymon Miks, 15 min)
It maps each double type from the theory onto Python code built with unittest.mock.
- Stop Calling Everything a Mock: A Practical Vocabulary for Test Doubles in Python (article, DEV Community, 10 min)
A decision flowchart and an in-memory fake example show when to prefer a fake or stub over a mock. The post is in Vietnamese, but the code and flowchart are readable without it.
- unittest.mock — mock object library (reference, Python docs, 45 min)
The official reference for Mock, MagicMock, patch, side_effect and autospec. Read the quick-guide sections first, then the 'Where to patch' section.
- Understanding the Python Mock Object Library (tutorial, Real Python, 40 min)
A guided walkthrough of patch() as a decorator and a context manager, with worked examples of where to patch.
- Why your mock doesn't work (blog, Ned Batchelder, 10 min)
It explains the most common mocking bug, patching the wrong name, by showing how Python name references work.
- Why your mock still doesn't work (blog, Ned Batchelder, 8 min)
It covers decorator argument order and why autospec=True catches mocks that don't match the real object.
- Why your mock breaks later (blog, Ned Batchelder, 8 min)
It shows how over-mocking a built-in like open can break other code, which is why you patch where an object is used.
- pytest-mock documentation (doc, pytest-mock, 15 min)
Once you know unittest.mock, the mocker fixture gives you the same tools with automatic cleanup, plus spy and stub helpers.
- pytest: How to mock in Python (article, Chang Hsin Lee, 20 min)
Practical recipes for mocking constants, class methods and slow API calls with mocker finish the path with hands-on patterns.