The test pyramid for a backend

Testing backends Junior Python 3.13+ PostgreSQL 17+ Reviewed By Best Latest Apps

Pick the fix

A bug in a JOIN reached production even though unit tests passed. The repository was mocked. Best fix?

Options
Hint 1 of 1

Did the SQL ever run in a test?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A Add integration tests that run repository queries against a real Postgres

Correct. Mocks never execute the SQL.

A mock returns what the test told it to, so the SQL never runs. Only a test against a real database checks the JOIN, its types and its NULL handling.

Why not the others?
  • B Add more mocked unit tests. They still don't run the query.
  • C Raise coverage to 100%. Coverage of mocked code doesn't test SQL.
  • D Only test manually. Slow and unrepeatable.

30-second answer

Many fast unit tests for logic, a solid layer of integration tests that hit real dependencies you own (the database, a real Redis), contract tests at service boundaries, and a few end-to-end tests of critical journeys. Backend bugs often live in SQL, serialisation and wiring, so integration tests against a real Postgres earn their cost more than in UI-heavy apps. Keep the whole suite fast enough to run on every pull request.

Practise saying it · 30 s. No recording, just a timer

Shape your test suite.

Say your answer out loud, then check which of these points you covered:

  • Unit for logic
  • Integration on real DB
  • Contracts at boundaries
  • Few E2E
  • Fast on every PR

Deep dive

Some teams prefer a 'testing trophy' weighted toward integration tests.

Test behaviour through public interfaces, not private helpers.

Run tests in parallel with isolated databases or schemas.

Measure flakiness and runtime, not just coverage.

Common mistakes

  • Mocking the database in every test, so SQL bugs reach production.
  • Hundreds of slow end-to-end tests.
  • Chasing 100% line coverage.

Senior take & follow-ups

Layers with their purpose, why backends lean on integration tests, and speed.

Follow-up questions

Think of your answer first, then open the hint.

  1. Why integration-heavy for backends?

    Show hint

    Many bugs are in queries and wiring that mocks hide.

  2. What's coverage good for?

    Show hint

    Finding untested areas, not proving correctness.

Suggest a fix if something here is wrong or out of date.