The backend testing pyramid

Fast unit tests on domain logic, integration tests against a real database (Testcontainers), contract tests at service boundaries. Mock the edges, not the DB.

About 27 min read3-question knowledge check

The mental model

Imagine building a car and choosing how to test it. You could only ever test by driving the finished car around a track — realistic, but slow, expensive, and when it fails you have no idea whether the fault is the spark plug, the gearbox, or the brakes. Or you could bench-test every individual bolt in isolation — fast and precise, but a car whose parts all pass individually can still fail to start. The sane answer is a mix weighted toward the cheap tests: check each component thoroughly on the bench, check that the components fit together in a few key assemblies, and drive the whole car only a handful of times.

That weighting is the testing pyramid: many fast unit tests at the base (test one piece of logic in isolation), fewer integration tests in the middle (test that pieces work together — your code against a real database, a real queue), and very few end-to-end tests at the top (drive the whole system). The shape is a pyramid because cost and slowness increase as you climb, so you want most of your confidence to come from the cheap layer.

The reason the shape matters — and the reason the inverted pyramid (or "ice cream cone": mostly slow E2E tests, few units) is a well-known anti-pattern — is feedback speed and failure localization. A unit test runs in milliseconds and tells you exactly which function broke. An E2E test runs in minutes, flakes intermittently, and when it fails you get "checkout is broken somewhere". A team whose test suite takes 40 minutes and fails randomly stops trusting it, stops running it, and ships bugs — the suite's purpose, catching regressions fast enough to act on, has been defeated by its shape.

The one backend-specific twist that this topic exists to teach: mock the edges, not the database. The instinct to mock everything for "unit purity" produces tests that pass while the real query is wrong. The modern practice — enabled by Testcontainers — is to run integration tests against a real Postgres in a container, because the database's behavior (constraints, transactions, SQL dialect, isolation) is precisely the part most likely to break and least faithfully reproduced by a mock.

The full lesson continues with 15 more sections
  • Deep dive
  • Internal architecture
  • Real-world use cases
  • Best practices
  • Common mistakes
  • Performance
  • Security
  • Production troubleshooting
  • Advantages & disadvantages
  • Alternatives
  • Interview expectations
  • Interview questions
  • Facts to remember
  • Cheat sheet
  • Quick revision