Lesson · Testing
Mocking Fundamentals
65 min readMocking Fundamentals
Mocks replace collaborators at a boundary so a test can control observations and responses. They are useful but easy to overuse; mocking implementation details creates brittle tests.
Learning goals
- Choose among fake, stub, and mock based on what the test needs to control or observe.
- Configure a
Mockwithreturn_valueand assert its usage withassert_called_once_with. - Know when
MagicMockis required and name one special method it covers. - Patch a name at its lookup site and explain why patching the definition site changes nothing.
- Decide where the boundary is and keep mocks off internal collaborators.
Mental model
A double stands in for one collaborator at the edge of your code, and the boundary decides whether the test stays honest: replace the outside world, not the internals the implementation happens to use today.
Mental model
read it top to bottom
what the test needs double
working simplified behavior fake (a small real class)
canned responses stub (return_value)
recorded and assertable interactions mock (Mock, MagicMock)
patch(name) replaces that name for the test, then restores it
^ patch where the code under test LOOKS THE NAME UP,
not where the name was originally definedCore idea
A test double stands in for a collaborator the test does not want to run for real, and the family divides by purpose: fakes implement simplified behavior, stubs return canned values, and mocks also record interactions for assertions. unittest.mock supplies the machinery, with patch swapping a name for the duration of a test and Mock or MagicMock providing the recording doubles. The line that keeps this honest is the boundary: replace what the code reaches outward to, not the internals it happens to use today.
Test doubles
A test double stands in for a collaborator. Fakes provide working simplified behavior, stubs provide canned responses, and mocks additionally record or assert interactions.
unittest.mock
unittest.mock is the standard library module that supplies test doubles: Mock and MagicMock for recording interactions, patch for temporary replacement, and helpers such as sentinel and call. It covers both configuring responses and asserting how a double was used.
Mock
Mock creates a configurable double: attribute access builds child mocks on demand, return_value sets what calls return, and every call is recorded in call_args_list for assertions such as assert_called_once_with. It accepts any signature, so it never enforces the collaborator's real interface.
MagicMock
MagicMock extends Mock with preconfigured support for special methods such as __len__, __iter__, and __enter__, so the double can be passed to len(), iterated, or used in a with block. Reach for it when the collaborator is used through protocols rather than plain method calls.
patch
unittest.mock.patch temporarily replaces a name at the location where the code under test looks it up. Patching the definition site instead of the lookup site is a common mistake.
Mocking boundaries
Mock at the boundary where the code under test reaches the outside world, such as a payment gateway, a clock, or an HTTP client, and keep the double on your side of that line. Mocking a boundary lets the test control responses and observe calls, while mocking an internal helper only restates the implementation.
Walkthrough
gateway = Mock()builds an object that accepts any attribute access and any call, andgateway.chargeis itself a child mock created on first use.gateway.charge.return_value = "payment-123"makes the next call tochargereturn that string, soresultholds a payment id without any payment logic running.gateway.charge(2500, currency="INR")is recorded incall_args_list, andassert_called_once_with(2500, currency="INR")passes because the exact call matched; a different keyword or a second call would make it fail.- Predict before running: the printed value, what happens to the assertion if
chargeruns a second time, and whatgateway.charge.call_argscontains after the current call.
Experiments to try
- Change the call's keyword to
currency="USD"but leave the assertion at"INR"; read theAssertionErrorand the actual call it reports. - Call
gateway.charge(2500, currency="INR")a second time and explain whyassert_called_once_withnow fails whileassert_any_call(2500, currency="INR")still passes. - Call
gateway.refund(500)without configuring it and print the result; explain why aMockreturns a child mock instead of raising. - Swap
Mock()forMagicMock()and comparelen(gateway)andlist(iter(gateway)); explain what the special methods return by default and what plainMockdoes with them.
Common mistakes
- Patching where a dependency is defined instead of where it is looked up:
patch("requests.get")cannot affect a module that ranfrom requests import get, because that module bound its own name to the original function at import time. - Asserting internal call sequences that are not part of the contract: the test fails on harmless refactors and passes while the outward behavior is wrong; assert outcomes and only the interactions the contract promises.
- Using a mock where a small fake is clearer: a fake with real simplified behavior exercises the calling code through genuine attribute access and iteration, while a mock accepts calls the real collaborator would reject.
- Leaking a patch: one applied with
start()and never stopped replaces the name for every later test; use thewithform or the decorator so the original is restored automatically.
Practice: Easy
- Run the worked example, then print
gateway.charge.call_argsandgateway.charge.call_count; match both against the single call the test made. - Change the call's keyword to
"USD"while the assertion stays"INR"and read the failure message; note that it prints the actual call, arguments included. - Set
gateway.refund.return_value = "ok", callgateway.refund(500)twice, and write assertions for the return value, the call count, and the arguments.
Practice: Medium
- Write
def make_purchase(gateway, amount, currency):that callsgateway.charge(amount, currency=currency)and returns"done"; test it with aMockgateway and assert both the gateway call and the returned string. - Compare that
Mockversion with a tinyRecordingGatewayclass that appends charges to a list; run the same function against both and state one thing each version checks that the other cannot. - Write a module-level
GATEWAY = Mock()consumed by a function, then replace it insidewith patch("module.GATEWAY") as fake:; confirm the original is restored after the block.
Practice: Hard
- Build a two-module example: one module defines
fetch_price, another imports it withfrom ... import fetch_priceand calls it; patch the consumer's name and show the consumer sees the double while the definition module keeps the real function. - Failure lab: patch the definition site and watch the real function run anyway, break an assertion on call order and explain why a behavior-preserving refactor fails it, and leak a
start()ed patch into a second test; explain each mechanism. - Decide fake or mock for three collaborators, a clock, a payment gateway, and an internal formatter; justify each from the boundary rule and from what the test needs to observe.
Lesson checklist
- I can choose fake, stub, or mock from what the test needs to control or observe.
- I can configure a
Mockwithreturn_valueand assert its usage withassert_called_once_with. - I can say when
MagicMockis required and name a special method it covers. - I can patch at the lookup site and explain why the definition site leaves the code unchanged.
Remember
A test double replaces a collaborator: fakes implement simplified behavior, stubs return canned values, and mocks record interactions for assertions. `unittest.mock` provides the recording doubles and `patch`, which swaps a name at its lookup site for the duration of a test. The judgment call is placement: mock what the code reaches outward to, and keep assertions on the outcomes the contract promises.
Interview angles
What is the main purpose of **Test doubles**?+
A test double stands in for a collaborator. Fakes provide working simplified behavior, stubs provide canned responses, and mocks additionally record or assert interactions.
What should you pay attention to when using **unittest.mock**?+
unittest.mock is the standard library module that supplies test doubles: Mock and MagicMock for recording interactions, patch for temporary replacement, and helpers such as sentinel and call. It covers both configuring responses and asserting how a double was used.
How does **Mock** fit into this lesson?+
Mock creates a configurable double: attribute access builds child mocks, return_value sets what calls return, and every call is recorded in call_args_list for assertions such as assert_called_once_with. It accepts any signature, so it never enforces the collaborator's real interface.
Why does patching `requests.get` fail to affect a module that used `from requests import get`?+
The from import bound the original function into that module's own namespace at import time, so patching the definition module cannot change that binding. Patch the name where the code under test looks it up, such as mymodule.get.