Skip to content

Lesson 22 of 28Quality and safety

Testing Strategy

Choose the right mix of unit, integration and end-to-end tests, use test doubles well, and test at architecture seams.

18 min read0/5 questions

You have built layers, ports, modules and events. This unit is about keeping them correct and safe as they change, and it starts with tests. A test suite is only useful if people trust it and it runs fast enough to run all the time. Too few tests and every deploy is a gamble. The wrong kind of tests and you have a 40-minute suite that fails randomly and breaks every time you rename a function. Testing strategy is choosing what to test, at which level, with which tools. Every architecture choice in this track (layers, ports, injected dependencies) pays off here.

Unit, integration, end-to-end

LevelWhat it exercisesTypical speedTools
UnitOne function or class, dependencies fakedMillisecondspytest, Vitest, Jest
IntegrationSeveral real parts together: service + real Postgres, route + real app10 ms to 1 spytest + Docker, FastAPI TestClient, Testing Library
End-to-end (E2E)The whole deployed system through a real browserSeconds eachPlaywright, Cypress

Higher levels catch more real-world bugs per test (wiring, SQL, CSS that hides a button) but are slower, flakier and harder to debug. Lower levels are fast and precise but can all pass while the app is broken.

Pyramid and trophy

The classic test pyramid (from Mike Cohn, around 2009) says: many unit tests, fewer integration tests, very few E2E tests.

The test pyramid
  1. E2Ea handful: sign up, check out, the money paths
  2. Integrationdozens to hundreds: routes, repositories, real DB
  3. Unithundreds to thousands: domain rules, services with fakes

The wide base: fast, isolated tests of domain rules and services. They run on every save in under a few seconds.

1/3

The testing trophy (popular in the React world) argues for more integration tests and a static-analysis base:

The testing trophy
  1. E2Ea few critical journeys
  2. Integrationthe biggest slice: components with real children, routes with real app
  3. Unitpure logic: formatters, reducers, rules
  4. StaticTypeScript, ESLint, mypy: catch typos and type errors for free

They agree more than they disagree: lots of fast tests, a few slow ones, and test behaviour that users or callers can observe. The trophy simply notes that in UI code, "render the component with its real children" catches more bugs per test than mocking every child.

Quick check
A team has 30 Playwright tests and 10 unit tests. The suite takes 25 minutes and fails randomly about once a day. What is the best first move?
Need a nudge? A hint rules out a wrong answer.

Test doubles

A test double stands in for a real dependency in a test, like a stunt double. The names are precise, and mixing them up is a common interview stumble.

  • Stub: returns canned answers. "The clock says it is day 10." It never fails a test by itself.
  • Spy: records how it was called so the test can check afterwards. "send was called once, with ada@example.com."
  • Mock: pre-programmed with expectations and fails if the calls do not match. unittest.mock.Mock and vi.fn() are often used as spies or mocks.
  • Fake: a working, simplified implementation. An in-memory repository with a dict instead of Postgres.
  • Dummy: passed only to fill a parameter, never actually used.
Python
from unittest.mock import Mock class StubRates: # stub: canned answer def rate(self, currency): return 0.5 class SpyMailer: # spy: records calls def __init__(self): self.calls = [] def send(self, to, text): self.calls.append((to, text)) class FakeOrders: # fake: real behaviour, in memory def __init__(self): self.rows = {} def save(self, order): self.rows[order["id"]] = order def get(self, order_id): return self.rows.get(order_id) def checkout(order, rates, orders, mailer): order["eur"] = round(order["usd"] * rates.rate("EUR")) orders.save(order) mailer.send(order["email"], f"Total: {order['eur']} EUR") rates, orders, mailer = StubRates(), FakeOrders(), SpyMailer()checkout({"id": 1, "usd": 80, "email": "ada@example.com"}, rates, orders, mailer)print(orders.get(1)["eur"])print(mailer.calls) mock_mailer = Mock() # mock: library-generated, assert on callscheckout({"id": 2, "usd": 10, "email": "sam@example.com"}, rates, orders, mock_mailer)mock_mailer.send.assert_called_once_with("sam@example.com", "Total: 5 EUR")print("mock expectations met")
Output
Press Run (⌘ Enter) to see what happens.
Match the pairs0/5 matched

Match each test double to what it does.

Choose an item, then its match on the other side.

Test at the architecture seams

A seam is a place where you can swap one implementation for another without editing the code under test. In the layered and hexagonal designs earlier in this track, every port is a seam: OrderRepository, PaymentGateway, Mailer. That is why the service layer is so easy to unit test: hand it fakes.

One risk remains. What if the fake behaves differently from the real thing? The fix is a contract test for the fake: one shared set of tests that runs against both implementations.

tests/contract/test_order_repository.py
import pytest
 
@pytest.fixture(params=["memory", "postgres"])
def repo(request, pg_session):
    if request.param == "memory":
        return InMemoryOrderRepository()
    return SqlOrderRepository(pg_session)
 
def test_saved_order_can_be_loaded(repo):
    repo.add(Order(id=1, total_cents=500))
    assert repo.get(1).total_cents == 500
 
def test_missing_order_returns_none(repo):
    assert repo.get(999) is None

If both pass, your fast unit tests that use the fake are trustworthy.

Between services, consumer-driven contract tests (with a tool like Pact) do the same across teams: the consumer writes down the requests it sends and the responses it relies on, and the provider's CI verifies it still honours them. That catches "billing renamed amount to amount_cents" before deploy, without spinning up both services together.

Predict the outputPython

What does this print?

class Spy:
  def __init__(self):
      self.calls = []
  def send(self, to):
      self.calls.append(to)

def notify(users, mailer):
  for u in users:
      if u["opted_in"]:
          mailer.send(u["email"])

spy = Spy()
notify([{"email": "a@x.io", "opted_in": True},
      {"email": "b@x.io", "opted_in": False},
      {"email": "c@x.io", "opted_in": True}], spy)
print(len(spy.calls), spy.calls[-1])
Need a nudge? Hints walk you through it.

What to test in FastAPI and React

FastAPIReact
UnitDomain rules and services with fake repositoriesPure helpers, reducers, custom hook logic
IntegrationRoutes via TestClient or httpx.AsyncClient, with app.dependency_overrides; repositories against real Postgres in DockerComponents rendered with Testing Library, queried by role and label, network mocked with MSW
E2ERarely alone; covered by the frontend's Playwright testsPlaywright: sign up, log in, checkout
AvoidTesting Pydantic or SQLAlchemy themselvesAsserting on internal state, CSS classes or snapshot dumps of whole pages

In React, Testing Library's guiding rule is "the more your tests resemble the way your software is used, the more confidence they give you". Find the button by its role and name, click it, and assert on what the user sees.

Quick check
Which React test will survive a refactor that renames internal state and splits a component in two?
Need a nudge? A hint rules out a wrong answer.

Tests in CI

Continuous integration runs the suite on every push and pull request. Order the jobs cheapest and fastest first, so a typo fails in 20 seconds instead of after a 10-minute E2E run.

.github/workflows/ci.yml
name: ci
on: [push, pull_request]
jobs:
  test:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:17
        env: { POSTGRES_PASSWORD: test }
        ports: ["5432:5432"]
    steps:
      - uses: actions/checkout@v4
      - uses: astral-sh/setup-uv@v6
      - run: uv sync
      - run: uv run ruff check . && uv run mypy app
      - run: uv run pytest tests/unit
      - run: uv run pytest tests/integration
        env: { DATABASE_URL: "postgresql://postgres:test@localhost:5432/postgres" }
Put it in order6 steps

Order a CI pipeline from first to last job.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
ChallengeEasy

Write a stub and a spy

send_trial_reminders(users, clock, mailer) (TypeScript: sendTrialReminders) is already written. It depends on a clock and a mailer, so to test it you need two test doubles:

  • StubClock(today): a stub. today() always returns the day number it was created with.
  • SpyMailer: a spy. send(to, subject) records each call in sent as a pair (to, subject) (TypeScript: a [to, subject] array). sent_to(address) (TypeScript: sentTo) returns how many messages went to that address.
clock = StubClock(10)
mailer = SpyMailer()
send_trial_reminders([{"email": "ada@x.io", "trial_ends": 12}], clock, mailer)  ->  1
mailer.sent  ->  [("ada@x.io", "Your trial ends soon")]

Days are plain integers so the tests are deterministic. That is the reason to stub a clock instead of calling the real date.

def send_trial_reminders(users: list[dict], clock, mailer) -> int: """Email every user whose trial ends in 0 to 3 days. Returns how many were sent.""" sent = 0 for user in users: days_left = user["trial_ends"] - clock.today() if 0 <= days_left <= 3: mailer.send(user["email"], "Your trial ends soon") sent += 1 return sentclass StubClock: def __init__(self, today: int): pass def today(self) -> int: pass class SpyMailer: def __init__(self): pass def send(self, to: str, subject: str) -> None: pass def sent_to(self, address: str) -> int: pass
Key terms
test pyramid
Many fast unit tests, fewer integration tests, very few end-to-end tests.
integration test
A test that runs several real components together, such as a route plus the real app, or a repository plus Postgres.
test double
Anything that stands in for a real dependency in a test: stub, spy, mock, fake or dummy.
fake
A working, simplified implementation (like an in-memory repository) used instead of the real one.
seam
A point where an implementation can be swapped without editing the code under test, such as an injected port.
contract test
A test that checks two sides (a fake and the real thing, or two services) agree on the same behaviour.