PRINCIPALCHAPTER 35

What not to test: the tests that cost more than they protect

Every test costs time to run, time to read and time to fix when the code moves. Measure what each one buys, delete the ones that buy nothing, and write the rule a new test must meet

55 MINSOFTWARE TESTING AND QUALITYUPDATED 2026-11-24
PREDICT

A suite has 37 tests that take 2.3 seconds. Fourteen of them are tests of mock call order, a whole-page snapshot, the framework's own behaviour, sleeps and calls with no assertion. You delete all fourteen and add six tests that check results (the order saved, the stock, the amount charged). What happens to the number of faults the suite catches, out of a set of eight small faults in the ordering code?

You have spent the course learning to add tests: boundaries, doubles, properties, fuzzing, contracts. Every one of them is right somewhere. This chapter is the other half of the craft: knowing when a test is wrong for its cost. It matters most in the third year of a codebase, when the suite is big enough that people stop reading it.

Every test has a price

A test costs four things.

  1. Run time. Seconds on your laptop, and minutes on CI when thousands run on every pull request. CI at scale makes that cost explicit.
  2. Read time. When it fails someone has to understand it. What a good test looks like is about making that cheap.
  3. Change time. When the code is changed on purpose the test must be changed too. This is the cost people forget, and the one that grows with the suite.
  4. Trust. A test that fails on harmless changes, or never fails at all, spends the team’s belief that red means something. Flaky tests is the extreme case, but a stable test that is red on every refactor does the same damage.

A test pays for those costs by one thing: the faults it catches that nothing else would. That is its protection. A test that protects nothing and costs something has a negative value, and a suite is the sum of its tests.

Two names help. Kent Beck’s Test Desiderata lists twelve properties a test can have. Two of them are in tension with the testing habits many teams grow into: behavioural (the test is sensitive to changes in the behaviour of the code) and structure-insensitive (it is not sensitive to changes in the code’s structure). Vladimir Khorikov, in Unit Testing: Principles, Practices, and Patterns, calls a test that fails when behaviour has not changed brittle. A suite with many brittle tests has a low rate of true failures, and people stop investigating failures.

Five kinds of test that usually lose

The lab builds one of each. None is wrong in every case. Each is the shape a test takes when it is written without asking what fault it catches.

1. A test of implementation. It checks how the code does its work: that a helper was called, in this order, with these arguments, a given number of times. Here is one from the checkout service:

payments.charge.assert_called_once_with("key-1", 902_500, "key-1")

It looks sensible, and half of it is. That the customer is charged once, for ₦9,025, is behaviour: charging twice or for the wrong amount loses money. That the reference sent to the provider equals the idempotency key is a choice. The day someone writes "order-" + key, nothing that matters has changed, and the test is red. Fakes, stubs and mocks calls this an interaction check and shows the same failure; here you will count it. Google’s Testing on the Toilet post “Test Behavior, Not Implementation” puts the rule in one line: tests should not need to change when user-facing behaviour does not.

2. A whole-output snapshot. It stores the page, or the response, and fails on any difference. A snapshot is cheap to write and costly to read, because a failure is a diff of a whole page and the habit is to accept it. The lesson on snapshot tests shows what happens in a 412-line diff. A snapshot is a good tool for a small output that you read in review. A whole HTML page is not that.

▶ SIMULATION
TEST
snapshot: 412 lines, every field
noise fails it: 0 time(s)
CHANGES THIS WEEK
none yet
PRODUCTION
price: 19.99 GBP
aria-label: Add Trail Runner to basket
last—
✓ the build is red exactly when something that matters changed✓ no regression in price or accessibility reaches production
SCHEDULE
01[TEST]test: snapshot the whole response (412 lines)
02[DEV]change: updatedAt reads 09:41
03[REVIEW]red build: run update snapshots
04[DEV]change: refactor reorders the keys
05[REVIEW]red build: run update snapshots
06[DEV]change: price 1999 becomes 199
07[REVIEW]red build, the same as the last two: update snapshots
08[DEV]change: the aria-label disappears
09[REVIEW]red build: update snapshots
10[TEAM]report
Start of break: 412-line snapshot scenario. 10 steps.
// 412 lines, recorded once, updated with `jest -u` whenever it goes red.
it('renders the product', async () => {
  const res = await getProduct('sku-481');
  expect(res).toMatchSnapshot();
});

Watch which column the real regression ships in. Then ask which of your own snapshots you have ever read to the end.

3. A test of the framework. It checks that FastAPI returns 422 for a bad body, that a frozen dataclass cannot be changed, that a 404 is a 404. Those behaviours belong to libraries with their own test suites far larger than yours. Your test adds nothing to theirs, and it breaks when you upgrade. The exception is your own configuration of the framework: a validation rule you wrote (qty must be at least 1) is your behaviour, and it deserves a test.

4. A slow test that guards nothing new. It sleeps for a fixed time to wait for something it could wait for exactly. The lab’s SearchIndex can be flushed, and the existing test does that in 0.13 seconds and covers more of the file than the sleeping version does in 1.66. The sleeping test is also the first step to a flaky one. Flaky tests covers the cure.

5. A test that runs code and checks nothing. It exists to raise coverage. The coverage chapter built one with suppress(Exception); quality metrics that mean something showed the target that caused it. It costs run time and a reader’s attention, and gives the number a false reading.

A sixth shape deserves a line, because the lab does not build it: the duplicate, a test that makes the same check as another at a different layer for no reason. It earns its place only if the layer fails differently. The shape of a suite says which layer should carry which check.

Measuring: what each file buys

“This feels like a waste” starts an argument. A number settles it, and three numbers are cheap to get.

Time. pytest --durations=5 lists the slowest tests. A test that is slow and unique is expensive and worth it. A test that is slow and not unique is the first to go. Add the time to read a failure and to change the test, which you can only estimate.

Faults caught uniquely. This is the number that matters. Take a set of small faults in the code you care about, apply them one at a time, and run each test file alone against each. A fault caught by one file only is that file’s unique kill. A file with none is either a duplicate, or tests something the faults do not reach, and you decide which.

This is mutation testing done by hand. The mutation tool in the lab, mutmut, does it for checkout/pricing.py and is described in the coverage chapter. It cannot be pointed at orders.py on a Mac, because mutmut forks a child per mutant and SQLite crashes in a forked child, which is why the lab runs it on the unit tests only. Eight faults you write yourself, in a 40-line script, give the same information for the code that touches the database.

Tests broken by a change that changes no behaviour. Make a refactor you could defend in review: rename an internal function, change how a string is built, add an attribute to an element. Run the suite. Every failure is a test that described the structure and not the behaviour. This is the cost in the change time line above, and it is easy to count.

None of the three counts the value of a test that guards a rare event. A test of the exact moment a promo ends costs one line and catches one bug a year; it is cheap in every column. Measure the expensive tests first.

Deleting, rewriting, keeping

Once you have the numbers, each test falls into one of four groups.

Group What the numbers say What to do
Unique kills, stable It catches a fault nothing else catches and survives refactors Keep it
Unique kills, but through the implementation Its one useful assertion is wrapped in structure checks Rewrite: keep the check of the result, drop the check of the call
No unique kills, fast and stable A duplicate that costs almost nothing Leave it, or fold it into a neighbour when you next touch it
No unique kills, slow or fragile It costs, and protects nothing others do not Delete it

The second row is the most useful. The mock test above caught one fault nothing else did (the cart was charged the subtotal and not the total), and its other assertions only measure how the code is built. The fix is to move that one check into a test of results: the charge the stub recorded equals the order’s total. A stub that records calls is a state check on a fact that matters, not an interaction check on the code’s wording.

Two cautions. Do not delete by speed alone. The slowest tests in a suite are usually the browser and integration tests that catch what unit tests cannot, and end-to-end and browser tests is a reminder that a few of them are worth their price. Do not trust a mutation score alone. A survivor can be an equivalent mutant, and a test that kills a mutant on code nobody cares about is not valuable. The numbers inform a decision; a person makes it.

A third caution is about the opposite mistake. David Heinemeier Hansson’s 2014 post “TDD is dead. Long live testing.” argued that heavy mocking and unit-level isolation bent his designs, and Beck, Fowler and Hansson went through the argument in a public series. You do not need to take a side on test-driven development to take the useful part: if a test forces you to add indirection to the code only so that it can be tested, that is a cost of the test, and a database test against a real SQLite file (as in integration tests with a real database) can be the cheaper choice.

What the lab shows

You will add the five kinds above to the starter suite, and nothing in it will look wrong: all 37 tests pass. Then you will measure them. The pattern in this lab’s numbers (and your own will match them closely, but not to the digit) is the one you will see in a real suite:

Habit suite After the cull
Tests 37 29
Run time about 2.3 s about 0.7 s
Faults caught of 8 (hand-made, in orders.py) 5 8
Mutants killed in pricing.py (mutmut) 28 of 68 28 of 68
Tests broken by three behaviour-neutral refactors 3 0
Line coverage of checkout/ 81% 82%

Eight fewer tests, a third of the time, three more faults caught, and no test broken by a refactor. The fourteen deleted tests were the cost. Nothing the suite protected was lost, because they protected none of it that the six new ones do not protect better. This is a small lab and the numbers are tidier than a real suite’s. The method is the same one you would run on Tallowmere’s.

One more point: the mutation score of pricing.py did not move. Neither the padding tests nor the snapshot touch a mutated line in a way that is checked. Mutation score is a tool for the code it mutates, not a measure of the whole suite.

The rule for a new test

Culling once is a one-off. The rule is what keeps the suite from refilling. Put it where review happens: the pull request template, or a short file next to the tests. A new test says, in one sentence each:

  1. The behaviour it protects, in words a product person would use (“a retry with the same key returns the first order”).
  2. The fault it would catch, specific enough to apply: “an order saved with the net and not the total”.
  3. Why no existing test catches that fault. If one does, extend it or leave it.
  4. What it costs: seconds, and whether it depends on structure (a patched helper, a file saved last time, a sleep).
  5. How it will fail: the message a reader sees at 02:10.

If the author cannot name the fault in item 2, the test is not ready. That is the single most useful check, and it takes ten seconds. It also gives the reviewer something to push back on that is not taste.

Two practical limits keep the rule honest. It applies to a new test and to a change to an existing test: updating a snapshot is a change, and the rule asks what the new snapshot protects. And it is a conversation, not a gate: for a bug fix, the test that reproduces the bug passes the rule by definition (item 2 is the bug).

LAB Cull the suite ~50 MIN
YOU NEEDPython 3.9+ with the lab set up (README, 'Set up')labs/testing, with .venv createda clean checkout: no files left from earlier chapters' labs in tests/

You will add five kinds of low-value test to the starter suite, measure what they cost and catch, break them with refactors that change nothing, then delete and rewrite them and measure again. Ojaline’s checkout service stands in for Tallowmere’s order code: the faults and refactors are in checkout/orders.py. Work from labs/testing. The tests use temporary databases, so nothing here touches data/.

cd labs/testing
.venv/bin/pytest -q
23 passed, 1 skipped, 1 deselected, in about a second. That is the starter suite on clean code. If you did the labs of earlier chapters and left files in tests/, remove them first so your numbers match.

1. Add the five habits. Create these files. Each is a test someone could write on a good day. The first three need the database, so they go under tests/integration/, where mutmut does not run them (it crashes when SQLite is used after a fork).

Create tests/integration/test_orders_interactions.py:

"""Tests of how place_order talks to its neighbours, not of what it achieves."""

from unittest.mock import Mock, patch

import checkout.orders as orders
from checkout.orders import place_order

ITEMS = [{"product_id": 2, "qty": 2}]

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

def test_helpers_are_called_in_this_order(db, clock, payments):
    manager = Mock()
    with patch.object(orders, "quote_lines", wraps=orders.quote_lines) as quote, \
         patch.object(orders, "reserve_all", wraps=orders.reserve_all) as reserve:
        manager.attach_mock(quote, "quote_lines")
        manager.attach_mock(reserve, "reserve_all")
        place_order(db, payments, clock, ITEMS, "key-2", distance_km=3)
    assert [call[0] for call in manager.mock_calls] == ["quote_lines", "reserve_all"]

def test_nothing_is_released_when_the_charge_succeeds(db, clock, payments):
    with patch.object(orders, "release_all") as release:
        place_order(db, payments, clock, ITEMS, "key-3", distance_km=3)
    release.assert_not_called()

Create tests/integration/test_framework_behaviour.py:

"""Tests of the libraries the service is built on."""

from dataclasses import FrozenInstanceError

import pytest
from fastapi.testclient import TestClient

from checkout.api import create_app
from checkout.pricing import Line, Quote
from checkout.search_index import SearchIndex

@pytest.fixture
def client(db, payments, clock):
    return TestClient(create_app(db, payments, clock, SearchIndex()))

def test_fastapi_rejects_a_quantity_that_is_a_word(client):
    body = {"lines": [{"product_id": 2, "qty": "two"}], "distance_km": 3}
    assert client.post("/cart/price", json=body).status_code == 422

def test_fastapi_has_no_route_called_nothing(client):
    assert client.get("/nothing").status_code == 404

def test_a_quote_cannot_be_changed(clock):
    quote = Quote(1, 2, 3, 4, 5, 6, 7)
    with pytest.raises(FrozenInstanceError):
        quote.total = 0

def test_a_line_remembers_what_it_was_given():
    line = Line(250_000, 3)
    assert (line.unit_price_kobo, line.qty) == (250_000, 3)

Create tests/integration/test_checkout_page_snapshot.py:

"""The whole checkout page, compared with a file saved last time."""

from pathlib import Path

from fastapi.testclient import TestClient

from checkout.api import create_app
from checkout.search_index import SearchIndex

SNAPSHOT = Path(__file__).resolve().parents[1] / "snapshots" / "checkout_page.html"

def test_checkout_page_matches_the_snapshot(db, payments, clock):
    client = TestClient(create_app(db, payments, clock, SearchIndex()))
    html = client.get("/").text
    if not SNAPSHOT.exists():  # first run writes it; later runs compare
        SNAPSHOT.parent.mkdir(exist_ok=True)
        SNAPSHOT.write_text(html)
    assert html == SNAPSHOT.read_text()

Create tests/integration/test_search_waits.py:

"""Search finds a product after the index lag, waiting with sleep."""

import time

import pytest

from checkout.search_index import SearchIndex

@pytest.mark.parametrize("name", ["ankara", "shea", "aso-oke"])
def test_product_is_searchable_after_waiting(name):
    index = SearchIndex(lag_s=0.2, jitter=False)
    index.submit({"id": 1, "seller_id": "s", "name": name, "status": "published"})
    time.sleep(0.5)
    assert [d["id"] for d in index.search(name)] == [1]

Create tests/unit/test_pricing_padding.py:

from contextlib import suppress
from datetime import datetime, timezone

from checkout.pricing import Line, delivery_fee, line_total, price_cart

def test_zero_quantity_runs():
    with suppress(Exception):
        line_total(Line(250_000, 0))

def test_negative_distance_runs():
    with suppress(Exception):
        delivery_fee(-5)

def test_promo_cart_runs():
    with suppress(Exception):
        now = datetime(2026, 12, 15, 12, 0, tzinfo=timezone.utc)
        price_cart([Line(300_000, 2)], distance_km=3, now=now, promo_code="HARMATTAN")
.venv/bin/pytest -q
37 passed, 1 skipped, 1 deselected in about 2.3 seconds (2.2 to 2.4 on three runs). Fourteen new tests, all green, and the suite takes more than twice as long. Nothing looks wrong yet.

2. Measure the cost. Time first, then coverage, then mutation.

.venv/bin/pytest -q -p no:randomly --durations=5 | grep -E "s (call|setup)"
.venv/bin/pytest -q -p no:randomly --cov=checkout --cov-branch | grep -E "^TOTAL"
rm -rf mutants
.venv/bin/python scripts/mutate.py run 2>&1 | tr '\r' '\n' | grep -o '[0-9]*/[0-9]* .*🔇 [0-9]*' | tail -1
0.51s call     tests/integration/test_search_waits.py::test_product_is_searchable_after_waiting[aso-oke]
0.51s call     tests/integration/test_search_waits.py::test_product_is_searchable_after_waiting[ankara]
0.51s call     tests/integration/test_search_waits.py::test_product_is_searchable_after_waiting[shea]
...
TOTAL    442    75    66    7    81%
68/68  🎉 28 🫥 0  ⏰ 0  🤔 0  🙁 40  🔇 0

The three sleeping tests are 1.5 of the 2.3 seconds. Coverage reads 81% and the mutation score on pricing.py is 28 of 68, exactly what it was before the padding tests (the starter suite alone scores 28 as well). Nothing you added has moved the mutation score by one mutant.

3. Count the faults only each file catches. Create scripts/by_hand.py. It applies eight small faults to checkout/orders.py, one at a time, runs each test file alone against each, and always restores the file.

"""Apply small hand-made faults to checkout/orders.py, one at a time, and record which test files catch each."""

import pathlib
import subprocess
import sys

TARGET = pathlib.Path("checkout/orders.py")
FAULTS = {
    "charge the subtotal, not the total": ("payments.charge(idempotency_key, quote.total,", "payments.charge(idempotency_key, quote.subtotal,"),
    "save the net, not the total":        ("db.save_order(idempotency_key, quote.total,", "db.save_order(idempotency_key, quote.net,"),
    "ignore the idempotency key":         ("if existing is not None:", "if False:"),
    "sell draft products":                ('product["status"] != "published"', "False"),
    "accept a declined charge":           ('if charge.status != "succeeded":', "if False:"),
    "never release stock":                ("release_all(db, lines)\n    order", "pass\n    order"),
    "never reserve stock":                ("    reserve_all(db, lines)\n", "    pass\n"),
    "buy one of everything":              ('"qty": item["qty"],', '"qty": 1,'),
}

def run(files):
    out = subprocess.run([sys.executable, "-m", "pytest", "-q", "-x", "-p", "no:randomly", "-p", "no:cacheprovider", *files],
                         capture_output=True, text=True)
    return out.returncode != 0

def main(files):
    original = TARGET.read_text()
    killers = {}
    try:
        for name, (old, new) in FAULTS.items():
            assert original.count(old) == 1, name
            TARGET.write_text(original.replace(old, new))
            killers[name] = [f for f in files if run([f])]
    finally:
        TARGET.write_text(original)
    for name, found in killers.items():
        print(f"{len(found)}  {name}: {', '.join(pathlib.Path(f).name for f in found) or 'SURVIVED'}")
    only = {}
    for found in killers.values():
        if len(found) == 1:
            only[found[0]] = only.get(found[0], 0) + 1
    print("killed by one file only:", {pathlib.Path(f).name: only.get(f, 0) for f in files})
    print(f"faults caught: {sum(1 for k in killers.values() if k)} of {len(killers)}")

if __name__ == "__main__":
    main(sys.argv[1:])
.venv/bin/python scripts/by_hand.py tests/integration/test_place_order.py tests/integration/test_api.py \
  tests/integration/test_orders_interactions.py tests/integration/test_framework_behaviour.py \
  tests/integration/test_checkout_page_snapshot.py
1  charge the subtotal, not the total: test_orders_interactions.py
0  save the net, not the total: SURVIVED
0  ignore the idempotency key: SURVIVED
0  sell draft products: SURVIVED
1  accept a declined charge: test_place_order.py
1  never release stock: test_place_order.py
2  never reserve stock: test_place_order.py, test_orders_interactions.py
3  buy one of everything: test_place_order.py, test_api.py, test_orders_interactions.py
killed by one file only: {'test_place_order.py': 2, 'test_api.py': 0, 'test_orders_interactions.py': 1, 'test_framework_behaviour.py': 0, 'test_checkout_page_snapshot.py': 0}
faults caught: 5 of 8

Read it carefully. The “5 of 8” is what these five chosen test files catch together, not what the whole suite catches. Three faults survive: an order saved with the wrong total, a retry that is not recognised, a draft product on sale. The framework tests and the snapshot catch none of the eight. The interaction file catches one fault no other file catches, the charge of the wrong amount, and that is the one assertion worth keeping. (The padding and sleep files are not in the list: they test pricing.py and search_index.py, and none of the eight faults is there.)

4. Make three refactors that change nothing, and count the damage. Back up the two files first. Each refactor is one a reviewer would approve with no comment.

cp checkout/orders.py checkout/orders.py.orig
cp checkout/api.py checkout/api.py.orig

# R1: build the provider reference differently (the amount and the key are unchanged)
sed -i.bak 's/payments.charge(idempotency_key, quote.total/payments.charge("order-" + idempotency_key, quote.total/' checkout/orders.py
.venv/bin/pytest -q -p no:randomly | grep -E "^FAILED|[0-9]+ (passed|failed)" | sed 's/ - .*//'
cp checkout/orders.py.orig checkout/orders.py

# R2: rename an internal helper everywhere it is used
sed -i.bak 's/quote_lines/price_the_cart/g' checkout/orders.py checkout/api.py
.venv/bin/pytest -q -p no:randomly | grep -E "^FAILED|[0-9]+ (passed|failed)" | sed 's/ - .*//'
cp checkout/orders.py.orig checkout/orders.py; cp checkout/api.py.orig checkout/api.py

# R3: give the page heading an id
sed -i.bak 's#<h1>Ojaline checkout</h1>#<h1 id="title">Ojaline checkout</h1>#' checkout/api.py
.venv/bin/pytest -q -p no:randomly | grep -E "^FAILED|[0-9]+ (passed|failed)" | sed 's/ - .*//'
cp checkout/api.py.orig checkout/api.py
rm -f checkout/*.bak checkout/*.orig
FAILED tests/integration/test_orders_interactions.py::test_the_provider_is_charged_once_with_the_key_as_reference
1 failed, 36 passed, 1 skipped, 1 deselected
FAILED tests/integration/test_orders_interactions.py::test_helpers_are_called_in_this_order
1 failed, 36 passed, 1 skipped, 1 deselected
FAILED tests/integration/test_checkout_page_snapshot.py::test_checkout_page_matches_the_snapshot
1 failed, 36 passed, 1 skipped, 1 deselected

Three refactors, no change in what the service does, three red tests. Each failure is a message about structure (an assertion on the call, an AttributeError on a patched name, a diff of a page) with nothing about customers in it. The third one is the Tallowmere habit: a person sees red, runs the update, and moves on. The fourth test in the interaction file, nothing_is_released, would have gone red on a rename of release_all, and the page snapshot on any change to the markup.

5. Cull and rewrite. Delete the five files, then write the tests that check results. The snapshot is replaced by a check of the four element ids the page’s script reads, which is the only thing the browser test depends on.

rm tests/integration/test_orders_interactions.py tests/integration/test_framework_behaviour.py \
   tests/integration/test_checkout_page_snapshot.py tests/integration/test_search_waits.py \
   tests/unit/test_pricing_padding.py
rm -rf tests/snapshots

Create tests/integration/test_place_order_behaviour.py:

"""What place_order achieves, checked in its results: the order, the stock, the money."""

import pytest

from checkout.inventory import OutOfStock
from checkout.orders import PaymentDeclined, UnknownProduct, place_order
from checkout.payments_client import ChargeResult
from tests.conftest import StubPayments

ITEMS = [{"product_id": 2, "qty": 2}]  # 2 x N3,500 shea butter

def test_a_paid_order_is_saved_with_the_quoted_total_and_takes_stock(db, payments, clock):
    order, created = place_order(db, payments, clock, ITEMS, "key-1", distance_km=3)
    assert created is True
    assert order["total_kobo"] == 902_500
    assert order["charge_id"] == "ch_stub"
    assert db.stock_of(2) == 98
    assert [c[1] for c in payments.calls] == [902_500]  # the customer is charged the quoted total, once

def test_a_retry_with_the_same_key_returns_the_first_order_and_charges_nothing(db, payments, clock):
    first, _ = place_order(db, payments, clock, ITEMS, "key-2", distance_km=3)
    again, created = place_order(db, payments, clock, ITEMS, "key-2", distance_km=3)
    assert created is False and again["id"] == first["id"]
    assert len(payments.calls) == 1 and db.stock_of(2) == 98

def test_a_declined_card_saves_no_order_and_puts_the_stock_back(db, clock):
    declining = StubPayments(ChargeResult("", "declined", "insufficient_funds"))
    with pytest.raises(PaymentDeclined):
        place_order(db, declining, clock, ITEMS, "key-3")
    assert db.stock_of(2) == 100 and db.count_orders() == 0

def test_a_draft_product_cannot_be_bought(db, payments, clock):
    with pytest.raises(UnknownProduct):
        place_order(db, payments, clock, [{"product_id": 4, "qty": 1}], "key-4")
    assert payments.calls == []

def test_more_than_the_stock_is_refused_before_any_charge(db, payments, clock):
    with pytest.raises(OutOfStock):
        place_order(db, payments, clock, [{"product_id": 3, "qty": 6}], "key-5")
    assert payments.calls == [] and db.stock_of(3) == 5

Create tests/integration/test_checkout_page.py:

"""The page the browser test drives: only what its script depends on."""

from fastapi.testclient import TestClient

from checkout.api import create_app
from checkout.search_index import SearchIndex

def test_page_has_the_controls_its_script_reads(db, payments, clock):
    html = TestClient(create_app(db, payments, clock, SearchIndex())).get("/").text
    for element_id in ("product", "qty", "place", "result"):
        assert f'id="{element_id}"' in html

Notice what the new order tests assert: the order that exists, the stock that remains, the money the stub recorded. None names a helper. The stub’s calls list is a record of what was charged, which is a fact about money and not about wording.

.venv/bin/pytest -q
29 passed, 1 skipped, 1 deselected, in about 0.7 seconds (0.7 to 0.9 on three runs). Fourteen tests deleted, six added.

6. Measure again. The same four checks as before.

.venv/bin/python scripts/by_hand.py tests/integration/test_place_order.py tests/integration/test_api.py \
  tests/integration/test_place_order_behaviour.py tests/integration/test_checkout_page.py
.venv/bin/pytest -q -p no:randomly --cov=checkout --cov-branch | grep -E "^TOTAL"
rm -rf mutants
.venv/bin/python scripts/mutate.py run 2>&1 | tr '\r' '\n' | grep -o '[0-9]*/[0-9]* .*🔇 [0-9]*' | tail -1

Then repeat the three refactors from step 4 exactly as written.

1  charge the subtotal, not the total: test_place_order_behaviour.py
1  save the net, not the total: test_place_order_behaviour.py
1  ignore the idempotency key: test_place_order_behaviour.py
1  sell draft products: test_place_order_behaviour.py
2  accept a declined charge: test_place_order.py, test_place_order_behaviour.py
2  never release stock: test_place_order.py, test_place_order_behaviour.py
2  never reserve stock: test_place_order.py, test_place_order_behaviour.py
3  buy one of everything: test_place_order.py, test_api.py, test_place_order_behaviour.py
killed by one file only: {'test_place_order.py': 0, 'test_api.py': 0, 'test_place_order_behaviour.py': 4, 'test_checkout_page.py': 0}
faults caught: 8 of 8
TOTAL    442    68    66    7    82%
68/68  🎉 28 🫥 0  ⏰ 0  🤔 0  🙁 40  🔇 0

All eight faults are caught. Coverage went up a point because the new tests reach lines the habits never did. The mutation score of pricing.py is unchanged at 28 of 68, which is the starter suite’s gap and not this chapter’s: it is the work of the coverage chapter. All three refactors now end 29 passed, 1 skipped, 1 deselected.

7. Write the rule. Create tests/WHY.md, the five questions a new test must answer, in your own words, with one worked example from the file you wrote a step ago:

# Before you add a test

1. Behaviour it protects:
2. Fault it would catch:
3. Why no existing test catches it:
4. Cost (seconds; does it depend on a helper's name, a saved file or a sleep?):
5. How it fails (the message a reader sees):

Example: test_a_retry_with_the_same_key_returns_the_first_order_and_charges_nothing
1. A retry of an order never creates a second order or a second charge.
2. The idempotency check is skipped (`if False:`).
3. test_place_order.py never retries.
4. 0.01 s; uses only the stub's recorded charges and the database.
5. `assert len(payments.calls) == 1` fails with 2.
A file of about fifteen lines. Item 2 of your own example is the check: you should be able to point at a fault in scripts/by_hand.py’s list. If you cannot, the test fails the rule.

Take the guard off the useful assertion and see what it was worth. Delete the line ending # the customer is charged the quoted total, once from test_a_paid_order_is_saved_with_the_quoted_total_and_takes_stock, then run scripts/by_hand.py again on the same four files. The fault “charge the subtotal, not the total” now survives, with 7 of 8 faults caught. That one line is what the mock test did that mattered, and nothing else in the suite checks the amount charged: the order’s saved total comes from the same quote, not from what the provider was asked for. A cull that deletes the whole mock test without moving that line loses real protection. Put the line back before you go on.

Then put the lab back as you found it: rm -rf tests/snapshots mutants tests/WHY.md scripts/by_hand.py tests/integration/test_place_order_behaviour.py tests/integration/test_checkout_page.py, and check git status shows no change under checkout/.

DECIDE

Tallowmere's CI takes 26 minutes and about 70% of it is snapshot and mock-heavy tests. Yelena has the numbers: of 600 such tests, a hand-made fault run shows that about 40 catch something nothing else catches, and refactors break about 50 of them a quarter. The team has a release next week and nine engineers. Amelie asks what to do first.

READING
  1. POST
    Testing on the Toilet: Test Behavior, Not Implementation Google Testing Blog, 2013

    One page that states the rule this chapter measures: a test should not need to change when behaviour does not. Read all of it, it is short. Read 2026-11-24.

  2. POST
    TDD is dead. Long live testing. David Heinemeier Hansson, 2014

    The argument that test-first, mock-everything unit testing bent designs, and what he did instead: tests that hit a real database. Read it as one side of a debate, not as a rule. Read 2026-11-24.

  3. TALK
    Is TDD Dead? Kent Beck, David Heinemeier Hansson and Martin Fowler, 2014

    Five recorded conversations with written minutes. Read the minutes of episode 2 (test-induced design damage) and episode 4 (costs of testing); skip episode 5, &ldquo;Answering Questions&rdquo;. Read 2026-11-24.

  4. DOC
    Test Desiderata Kent Beck

    Twelve properties of a good test and the trade-offs between them. Read the behavioural and structure-insensitive entries against the five kinds of test above. Skip the rest on a first pass. Read 2026-11-24.

  5. BOOK
    Unit Testing: Principles, Practices, and Patterns Vladimir Khorikov, 2020

    The most developed argument for resistance to refactoring as the property that matters most, with a method for deciding what to keep. Read 2026-11-24. Read: The chapters on the four pillars of a good unit test and on brittle tests; skip the sections on a specific mocking library..

  6. POST
    Software Testing Anti-patterns Kostis Kapelonis, 2018

    A list of what teams do wrong. Read the entries on testing internal implementation, testing the wrong functionality and paying excessive attention to coverage; skip the rest. Read 2026-11-24.

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: Capstone: the quality strategy →