BEGINNERCHAPTER 04

Fakes, stubs and mocks, and when each one lies

Three ways to replace a dependency in a test, and the one thing none of them can promise: that the real thing still behaves like your copy

50 MINSOFTWARE TESTING AND QUALITYUPDATED 2026-11-23
PREDICT

Ojaline's provider renames the field status to state in its charge response. The checkout service has three tests of place_order: one with a stub that returns a canned ChargeResult, one with a Mock whose charge method returns Mock(status='succeeded'), and one with a hand-written fake provider that was copied from the old API. The provider's own contract file is updated to say state. Which of the three go red?

A unit test wants to be fast and to say one thing. The code under test often wants to talk to something that is neither: a database, a clock, a network service, a payment provider. You replace that something with a stand-in. The stand-in is called a test double, after the stunt double in a film. Gerard Meszaros named the family in xUnit Test Patterns; Martin Fowler’s article in the reading list popularised the vocabulary below.

The word people use for all of it is “mock”. That word is the source of most confusion, so this chapter starts by taking it apart.

Five kinds of double

Meszaros lists five. You will meet three daily.

Double What it does What you assert on
Dummy Fills a parameter that is never used. None, or an object that raises if touched. Nothing.
Stub Returns canned answers to calls. No logic. The result of the code under test (state).
Fake A working implementation that takes a shortcut: an in-memory database, a provider that keeps its charges in a dict. The result of the code under test (state).
Spy A stub that also records how it was called. State, and afterwards what was recorded.
Mock Pre-programmed with the calls it expects. Fails if the calls differ. The calls themselves (interaction).

Python’s unittest.mock.Mock is a spy that people also use as a stub and a mock. It answers any call with another Mock, records every call, and offers assert_called_once_with afterwards. So the library’s Mock is not one of the five; it is a tool you can use to build any of them. When someone says “I mocked the provider”, ask which kind they built. The answer changes what the test proves.

The deeper split is in the last column. A state check runs the code, then looks at what changed: the order exists, the stock went down by two, the charge id is stored. An interaction check looks at how the code talked to its neighbour: charge was called once, with these three arguments. A state check survives a refactor that keeps behaviour. An interaction check fails when the refactor changes how the code asks, even if what it achieves is identical. Hold on to that; step 2 of the lab makes it happen.

The checkout service, three ways

place_order in checkout/orders.py prices a cart, reserves stock, charges the provider and saves the order. It takes its provider as an argument. Anything with a charge(reference, amount_kobo, idempotency_key) method that returns a ChargeResult will do. That argument is a seam: a place where you can substitute behaviour without editing the code. Seams are what make doubles possible, and a function that builds its own PaymentsClient inside has none.

The lab’s tests/conftest.py already has a stub:

class StubPayments:
    def __init__(self, result=ChargeResult("ch_stub", "succeeded")):
        self.result = result
        self.calls = []

    def charge(self, reference, amount_kobo, idempotency_key):
        self.calls.append((reference, amount_kobo, idempotency_key))
        return self.result

It returns whatever you give it. A test with it says: given a provider that approves, place_order prices the cart at ₦9,025 (902,500 kobo) and stores the charge id. Nothing more, and nothing less to maintain. Stubs are the right default when the dependency’s answer matters and its behaviour does not.

A fake earns its keep when the behaviour matters. The provider dedupes a charge by Idempotency-Key. It declines a card with too little money. It keeps charges you can count afterwards. You can express none of that with a stub without hard-coding each answer in each test. A fake holds the rules once:

class FakeProvider:
    def __init__(self, limit_kobo=10_000_000):
        self.limit_kobo = limit_kobo
        self.charges = {}
        self.by_key = {}
    # handle(request) answers 402 over the limit, 200 for a repeated key, else 201

The lab version speaks HTTP through httpx.MockTransport, a hook the real PaymentsClient already accepts through its transport argument. That choice is deliberate. The fake sits underneath the real client, so a test through it runs the client’s own parsing, timeouts and error mapping. A stub placed above the client skips all of that code.

A mock in the strict sense verifies the conversation:

payments = Mock()
payments.charge.return_value = Mock(status="succeeded", id="ch_mock")
place_order(db, payments, clock, ITEMS, "key-4", distance_km=3)
payments.charge.assert_called_once_with("key-4", 902_500, "key-4")

This test is quick to write and it checks something real: the customer is charged once, for the right total. The same check with a stub would read payments.calls == [("key-4", 902_500, "key-4")]; with a fake it would be len(fake.charges) == 1. Notice that the fake version asserts on the result of the conversation and the mock version asserts on its exact words.

Where each one lies

Every double is a claim about a real thing. A claim can be wrong in four ways, and each kind of double has a favourite.

The stub lies about what can happen. A stub that always approves never meets a decline, a timeout or a duplicate. The code paths for those stay untested because the double cannot produce them. The fix is more stubs (one per outcome) or a fake that can produce all of them.

The fake lies by simplification. Ojaline’s provider has fees, settlement delays and a hundred error codes. The fake has a dict. Most of the time that is fine, because the test needs one behaviour and the fake supplies it. The fake lies when your code starts to depend on a behaviour the fake never copied. Software Engineering at Google gives this its own section, “The Fidelity of Fakes”, and its rule is blunt: fakes should be tested. The team that owns the real service ideally owns the fake, and a contract test runs against both.

The mock lies by freezing the conversation. assert_called_once_with("key-4", 902_500, "key-4") records that place_order passes the idempotency key as the charge reference. That is an implementation choice, not a requirement. The day someone writes "order-" + key there, the test fails and the behaviour is exactly as correct as before. A test that fails on a harmless change teaches the team to distrust red, and then to delete the test.

Every double lies by drift. This is the one that costs money. A double is written at a moment in time. The real service moves; the double does not. If the provider renames status to state, a stub with a ChargeResult("ch_stub", "succeeded") still works, a Mock(status="succeeded") still works, and a fake that emits "status" still works. All three agree with each other and with nobody else.

▶ SIMULATION
CONSUMER UNIT TESTS
mock: amount: number
runs: —
REAL PROVIDER RESPONSE
id: "inv_101"
amount: 48200
status: "paid"
PRODUCTION CHECKOUT
last call: —
deploys blocked: 0
last—
✓ no production call fails while the consumer's unit tests are green
SCHEDULE
01[CONSUMER]unit tests run against the hand-written mock
02[PROVIDER]provider renames amount to total
03[PROVIDER]provider deploys (its own tests pass)
04[CONSUMER]unit tests run again: the mock has not changed
05[CONSUMER]production checkout calls the real API
06[CI]report
Start of break: the provider renames a field scenario. 6 steps.
// The consumer's test owns the mock. Nothing ties it to the provider.
const mockBilling = { id: 'inv_101', amount: 48200, status: 'paid' };

test('shows the amount', () => {
  const page = render(mockBilling);
  expect(page.total).toBe('₦482.00');   // green forever
});

Watch the strip that shows the unit tests in the first three scenarios: green all the way through, while production is red. The simulation proves one thing: a green suite built on doubles says nothing about whether those doubles still match the provider. The lab reproduces it in Ojaline’s code and then closes the gap.

Making a mock less naive

Plain Mock() accepts every attribute and every call. Misspell assert_called_once_with and Python raises, because names beginning with assert are guarded. Misspell payments.chrage(...) and you get a new child mock and a silent pass.

create_autospec(PaymentsClient, instance=True) copies the real class’s names and signatures. Call charge with the wrong number of arguments and it raises TypeError. Ask for an attribute the class lacks and it raises AttributeError. That is a large improvement for almost no cost: Mock(spec=...) only checks attribute names, while autospec also checks how you call the thing.

Two limits matter. Autospec checks the call, not the answer. payments.charge.return_value is still whatever you set, so a Mock(status="succeeded") stays a lie about what the client returns. Build the return value from the real class (ChargeResult("ch_mock", "succeeded")) and a rename of that dataclass field is caught the moment your test constructs it. And autospec never sees the wire at all. If PaymentsClient reads body["status"] and the provider now sends state, the client is wrong in a way no Python-level double can show, because the double replaced the client.

One more rule from the Python docs, because it bites every beginner: patch where the name is looked up, not where it is defined. If orders.py does from payments_client import PaymentsClient, you patch checkout.orders.PaymentsClient, because that is the name place_order reads. Patching checkout.payments_client.PaymentsClient changes a name nobody is using. Passing the double in as an argument, which place_order already allows, avoids the question.

Keeping a double honest

You cannot stop a double drifting. You can arrange for drift to turn a test red. Three tools do it, from cheapest to dearest.

  1. A contract check on the double. The lab’s fake_provider/contract.json holds a JSON Schema for each provider response. Validate what your fake emits against it. When the contract changes, the fake’s test fails, and you update the fake on purpose. This is the same idea as the consumer-driven contract in the lesson above, run in the other direction: the fake is held to the contract, as the real provider is.
  2. A test through the real client. Place the double under the real PaymentsClient, as the lab’s fake does, so the client’s parsing runs. When the fake is brought up to date, any client code still reading the old field fails at once.
  3. A live check against the real service or its sandbox. In the lab that is scripts/smoke_test.py, which starts the fake provider and the API and places an order. It is slow and it needs the services, so it runs on every merge, not on every save. The later chapter on API and contract tests builds this layer properly.

Each layer catches something the one before cannot. None replaces the stub or the mock: a suite of 400 stub-based unit tests plus ten checks against the contract and the live provider is a good shape. A suite of 400 mocks and nothing else is the Thursday in the Why.

Choosing a double

Ask these questions in order.

  1. Does the test need the dependency at all? If the code is pure (pricing, in checkout/pricing.py), pass values in. No double. Pure code is the easiest to test, and a reason to move logic out of the part that talks to the world.
  2. Is the real thing cheap, fast and deterministic? Use it. An in-memory SQLite file is a real database; the lab’s db fixture uses one. Google’s guidance, “prefer realism over isolation”, is the same advice.
  3. Do you need one answer? A stub. Several behaviours that must stay consistent? A fake.
  4. Does the call itself matter, with no visible result? A charge that must happen exactly once, an email that must be sent, a metric that must be emitted. Use a spy or a mock, and assert on what matters (the amount and the key) without pinning how the code spells the rest.
  5. Always: can something compare the double with the real thing, now or on a schedule? If not, you have a copy with no warranty.

The pattern behind these questions is stated in the Testing on the Toilet post in the reading list: a test full of when(...).thenReturn(...) lines tests your assumptions about the neighbours more than it tests your code.

LAB The mock that stayed green ~40 MIN
YOU NEEDPython 3.9+ with the lab set up (README, 'Set up')labs/testing, with .venv createdabout 10 minutes of attention for the second half

You will test place_order with a stub, a fake and a mock. Then you will change the provider’s response field, watch which tests notice, and close the gap. Work from labs/testing. The tests use temporary databases and the smoke test makes its own, so nothing here touches data/.

cd labs/testing
.venv/bin/pytest -q
23 passed, 1 skipped, 1 deselected. That is the starter suite on clean code. Everything below adds to it.

1. Write the three doubles and three tests.

Create tests/fakes.py:

"""Hand-written test doubles."""

import json

import httpx


class FakeProvider:
    """A working in-memory provider. It speaks HTTP through httpx.MockTransport."""

    def __init__(self, limit_kobo=10_000_000):
        self.limit_kobo = limit_kobo
        self.charges = {}   # charge id -> body
        self.by_key = {}    # idempotency key -> charge id

    def transport(self):
        return httpx.MockTransport(self.handle)

    def handle(self, request):
        body = json.loads(request.content)
        key = request.headers.get("Idempotency-Key")
        if body["amount_kobo"] > self.limit_kobo:
            return httpx.Response(402, json={"error": "card_declined", "code": "insufficient_funds"})
        if key in self.by_key:
            return httpx.Response(200, json=self.charges[self.by_key[key]])
        charge = {
            "id": f"ch_fake{len(self.charges):05d}",
            "status": "succeeded",
            "amount_kobo": body["amount_kobo"],
            "currency": body["currency"],
            "reference": body["reference"],
        }
        self.charges[charge["id"]] = charge
        self.by_key[key] = charge["id"]
        return httpx.Response(201, json=charge)

Create tests/unit/test_place_order_doubles.py:

"""place_order three ways: a stub, a hand-written fake provider, a Mock."""

from unittest.mock import Mock

import pytest

from checkout.orders import PaymentDeclined, place_order
from checkout.payments_client import PaymentsClient
from tests.fakes import FakeProvider

ITEMS = [{"product_id": 2, "qty": 2}]  # 2 x N3,500 shea butter
TOTAL = 902_500                         # 700,000 net + 52,500 VAT + 150,000 delivery (3 km)


def test_stub_order_is_priced_and_paid(db, payments, clock):
    order, created = place_order(db, payments, clock, ITEMS, "key-1", distance_km=3)
    assert created is True
    assert order["total_kobo"] == TOTAL
    assert order["charge_id"] == "ch_stub"


def test_fake_declined_card_puts_the_stock_back(db, clock):
    fake = FakeProvider(limit_kobo=500_000)  # this card can pay at most N5,000
    client = PaymentsClient("http://provider.test", transport=fake.transport())
    with pytest.raises(PaymentDeclined) as err:
        place_order(db, client, clock, ITEMS, "key-2", distance_km=3)
    assert err.value.code == "insufficient_funds"
    assert db.stock_of(2) == 100
    assert fake.charges == {}


def test_fake_provider_charges_once_per_key():
    fake = FakeProvider()
    client = PaymentsClient("http://provider.test", transport=fake.transport())
    first = client.charge("ref", 1_000, "key-3")
    again = client.charge("ref", 1_000, "key-3")
    assert first.id == again.id
    assert len(fake.charges) == 1


def test_mock_charges_the_total_once(db, clock):
    payments = Mock()
    payments.charge.return_value = Mock(status="succeeded", id="ch_mock")
    order, _ = place_order(db, payments, clock, ITEMS, "key-4", distance_km=3)
    payments.charge.assert_called_once_with("key-4", TOTAL, "key-4")
    assert order["charge_id"] == "ch_mock"
.venv/bin/pytest tests/unit/test_place_order_doubles.py -v -p no:randomly
Four tests, all PASSED: 4 passed. The stub test and the mock test never touch HTTP. The two fake tests run the real PaymentsClient over httpx.MockTransport, so they run its JSON parsing and its 402 handling too.

2. Refactor harmlessly and see who complains.

In checkout/orders.py, change the charge call so the provider’s reference carries a prefix. The behaviour that matters (one charge, right total, same idempotency key) does not change:

        charge = payments.charge("order-" + idempotency_key, quote.total, idempotency_key)
.venv/bin/pytest tests/unit -q -p no:randomly
1 failed, 13 passed. The failure is test_mock_charges_the_total_once: Expected: charge('key-4', 902500, 'key-4') and Actual: charge('order-key-4', 902500, 'key-4'). The stub and fake tests do not care how the reference is spelt, because they check results. Put orders.py back to payments.charge(idempotency_key, quote.total, idempotency_key) before you go on.

3. Hold the fake to the contract.

Create tests/unit/test_fake_matches_contract.py. It checks one charge response from your fake and one from the lab’s own fake provider app against fake_provider/contract.json:

"""The hand-written fake must answer the way fake_provider/contract.json says."""

import json
from pathlib import Path

import httpx
import jsonschema
import pytest
from fastapi.testclient import TestClient

from fake_provider.app import app as provider_app
from tests.fakes import FakeProvider

CONTRACT = json.loads((Path(__file__).resolve().parents[2] / "fake_provider" / "contract.json").read_text())
CHARGE = {"$ref": "#/definitions/charge", "definitions": CONTRACT["definitions"]}
BODY = {"reference": "ref-1", "amount_kobo": 1_000, "currency": "NGN"}


def through_hand_written_fake():
    client = httpx.Client(base_url="http://provider.test", transport=FakeProvider().transport())
    return client.post("/v1/charges", json=BODY, headers={"Idempotency-Key": "k"})


def through_the_real_provider_app():
    client = TestClient(provider_app)
    client.post("/_admin/reset")
    return client.post("/v1/charges", json=BODY, headers={"Idempotency-Key": "k"})


@pytest.mark.parametrize("make_response", [through_hand_written_fake, through_the_real_provider_app])
def test_a_charge_response_matches_the_contract(make_response):
    resp = make_response()
    assert resp.status_code == 201
    jsonschema.validate(resp.json(), CHARGE)
.venv/bin/pytest -q
29 passed, 1 skipped, 1 deselected: the 23 starter tests plus your four doubles tests and two contract checks. Everything is green, which is the state of Ojaline’s suite on the Thursday morning.

4. The provider renames a field.

Pretend the provider ships state instead of status. Edit both of its files, fake_provider/contract.json (replace every "status" with "state": two places, in required and in properties) and fake_provider/app.py (the line "status": "succeeded", becomes "state": "succeeded",). Do not touch checkout/ or tests/.

.venv/bin/pytest -q -p no:randomly
1 failed, 28 passed, 1 skipped, 1 deselected. The one failure is test_a_charge_response_matches_the_contract[through_hand_written_fake], with jsonschema.exceptions.ValidationError: 'state' is a required property. The stub test, the mock test and both fake place_order tests are green: they all still describe the old provider. Only the check that compares a double with the contract noticed.

5. Ask the real service.

The smoke test starts the fake provider and the checkout API as separate processes and places a real order over HTTP. If port 8094 or 8095 is busy, set SMOKE_API_PORT and SMOKE_PROVIDER_PORT to free ones.

.venv/bin/python scripts/smoke_test.py > smoke.log 2>&1; echo "exit: $?"
grep -E "^(ok|OK|FAIL)|Error" smoke.log
exit: 1. The log holds KeyError: 'status' from the API, ok both apps answer and ok cart priced: 700,000 net + 52,500 VAT + 150,000 delivery, then a JSONDecodeError when the order request comes back as a plain-text 500. The real client reads body["status"] from the new provider and the key is gone. This is the failure the 400 mock-based tests hid. It costs a few seconds and two processes, which is why you run it on merge and not on every save.

6. Autospec, and how far it gets you.

First, with the rename from step 4 still in place, add this test to tests/unit/test_place_order_doubles.py (and add create_autospec to the unittest.mock import and ChargeResult to the checkout.payments_client import):

def test_autospec_mock_charges_the_total_once(db, clock):
    payments = create_autospec(PaymentsClient, instance=True)
    payments.charge.return_value = ChargeResult("ch_mock", "succeeded")
    order, _ = place_order(db, payments, clock, ITEMS, "key-5", distance_km=3)
    payments.charge.assert_called_once_with("key-5", TOTAL, "key-5")
    assert order["charge_id"] == "ch_mock"
.venv/bin/pytest tests/unit/test_place_order_doubles.py -q -p no:randomly
5 passed. Autospec did not notice the renamed wire field, and could not: the double replaced the client, so no HTTP happened. Now change the signature of the real client instead. In checkout/payments_client.py make currency a required argument, so the method line reads def charge(self, reference: str, amount_kobo: int, currency: str, idempotency_key: str) -> ChargeResult: and the request body uses "currency": currency in place of "currency": "NGN". Run the same command again: 3 failed, 2 passed. The autospec test fails with TypeError: missing a required argument: 'idempotency_key', the two fake tests that call the client fail too, and the stub test and the plain Mock test stay green. Autospec catches a changed method. A plain Mock does not. Put payments_client.py back as it was.
Fix the drift for real, so the double and the client move together. Make the fake emit "state" (in tests/fakes.py), then run .venv/bin/pytest tests/unit -q -p no:randomly: the contract check goes green and a new test fails, test_fake_provider_charges_once_per_key, with KeyError: 'status'. The fake found the client bug that the mock hid, because it runs the client’s parsing. Change body["status"] to body["state"] in checkout/payments_client.py; .venv/bin/pytest -q gives 30 passed, 1 skipped, 1 deselected and the smoke test ends with OK. Then ask yourself what the stub and the mock test were protecting while the suite was red everywhere else. When you are done, delete smoke.log, tests/fakes.py and the two new test files (test_place_order_doubles.py, test_fake_matches_contract.py), and undo your edits to fake_provider/ and checkout/ so the lab is as you found it.
DECIDE

Fatoumata's team wants to cover place_order's failure paths: a decline, a provider timeout, a provider 500 and a repeated charge. There are two options on the table. Gugu proposes four Mock-based tests that set side_effect and assert on calls. The team lead proposes extending the hand-written FakeProvider with modes. The real provider offers a sandbox that is down about once a week. What do you pick?

READING
  1. POST
    Mocks Aren't Stubs Martin Fowler, 2007

    The article that fixed the vocabulary of this chapter and the argument over state against interaction testing. Read 'The Difference Between Mocks and Stubs' and 'Classical and Mockist Testing'. Skip the EasyMock code unless you write Java.

  2. BOOK
    Test Double Gerard Meszaros

    The original definitions of the five kinds. The page says the book's text has since changed, so use it for the names and the intent, and the book (xUnit Test Patterns, page 522) for the current wording. Read: the pattern page and its links to Dummy Object, Test Stub, Test Spy, Mock Object and Fake Object.

  3. DOC
    unittest.mock: mock object library

    The reference for Mock, MagicMock, patch and create_autospec in Python 3. Read the sections on autospeccing and on spec and spec_set; skip the long list of magic-method details on a first pass.

  4. DOC
    unittest.mock: where to patch

    The short section that explains why a patch has no effect when you patch the name where it is defined. It is the commonest mock bug in Python code reviews.

  5. BOOK
    Software Engineering at Google, chapter 13: Test Doubles Andrew Trenk and Dillon Bly, 2020

    The most careful account of when each double earns its cost, with the argument for fakes owned by the service's own team. Skip the Java-specific mocking-framework detail. Read: 'Prefer Realism Over Isolation', 'Faking' (including 'The Fidelity of Fakes' and 'Fakes Should Be Tested'), 'Stubbing' and 'Interaction Testing'.

  6. POST
    Testing on the Toilet: Don't Overuse Mocks Andrew Trenk, 2013

    A one-page before and after of a test crowded with mocks and the same test against a real object. Read it for the list of what overuse costs, then compare it with step 2 of the lab.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: Choosing cases: boundaries, equivalence classes and the unhappy path →