Mocking & patching (and its pitfalls)
P30.test-doubles.01 · Audience: guest, it-ml, language-pro · Prerequisites: pytest idioms
Some dependencies you cannot call in a test: a payment gateway, an email
server, the system clock, a random number. A test double stands in for
them - a Mock that records how it was used, swapped in with patch. Used at
the right boundary, doubles make a test fast and deterministic. Used
everywhere, they produce tests that pass while the code is broken. This module
builds both tools and then teaches the judgement to use them sparingly.
ⓘ Concept: Mock: stand in, then let you assert
gateway.assert_called_with(25). unittest.mock.Mock is the standard one; in rung 1 you build a minimal version, so .return_value, .call_count and call assertions hold no mystery.Why it matters — You cannot unit-test 'did checkout charge the card the right amount?' by charging a real card; a mock lets you assert the interaction without the side effect.
Ask the mentor about this module
Ask a question about this content. The mentor explains and grounds its answer in what you are studying; asking is recorded as a learning signal, not a grade.
🎓 Practice ladder
4 graded rungs · ~46 minYour turn: build a recording Mock, then the patch
swap-and-restore, critique a test that mocks so much it proves nothing, and
close with the interview on how much to mock.
Rung 1 - build a recording Mock
Loading exercise…
Rung 2 - build patch: swap an attribute, then restore it
Loading exercise…
Rung 3 - critique an over-mocked test (free-form)
Loading exercise…
Interview rung - when to mock, and the traps of over-mocking (free-form)
Loading exercise…
Doubles are the sharpest tool in a testing kit and the easiest to overuse. The skill is not writing mocks - it is knowing the one boundary in a function that deserves one, and leaving the rest real.
Where next?
Go up a level