Mocking & patching (and its pitfalls)
P30.test-doubles.01 · Audience: Guest, IT/ML learner, Language professional · Prerequisites: pytest idioms
Where next?
Go up a level
P30.test-doubles.01 · Audience: Guest, IT/ML learner, Language professional · Prerequisites: pytest idioms
Go up a level
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.
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 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.
Off by default. The mentor always gets your file; this only decides whether your own copy stays here. Copies live in this browser only - they do not follow you to another device, and clearing site data removes them.
Your 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.
Loading exercise…
Loading exercise…
Loading exercise…
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.
Loading your notes...