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.
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
| Level | What it exercises | Typical speed | Tools |
|---|---|---|---|
| Unit | One function or class, dependencies faked | Milliseconds | pytest, Vitest, Jest |
| Integration | Several real parts together: service + real Postgres, route + real app | 10 ms to 1 s | pytest + Docker, FastAPI TestClient, Testing Library |
| End-to-end (E2E) | The whole deployed system through a real browser | Seconds each | Playwright, 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 wide base: fast, isolated tests of domain rules and services. They run on every save in under a few seconds.
The testing trophy (popular in the React world) argues for more integration tests and a static-analysis base:
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.
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. "
sendwas called once, with ada@example.com." - Mock: pre-programmed with expectations and fails if the calls do not match.
unittest.mock.Mockandvi.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.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Match each test double to what it does.
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.
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 NoneIf 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.
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])What to test in FastAPI and React
| FastAPI | React | |
|---|---|---|
| Unit | Domain rules and services with fake repositories | Pure helpers, reducers, custom hook logic |
| Integration | Routes via TestClient or httpx.AsyncClient, with app.dependency_overrides; repositories against real Postgres in Docker | Components rendered with Testing Library, queried by role and label, network mocked with MSW |
| E2E | Rarely alone; covered by the frontend's Playwright tests | Playwright: sign up, log in, checkout |
| Avoid | Testing Pydantic or SQLAlchemy themselves | Asserting 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.
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.
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" }Order a CI pipeline from first to last job.
- Tap the steps below in the right order.
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 insentas 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.
- 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.