Video in progress

Senior 🧪 Testing

For a new Spring Boot service, how do you decide the ratio of unit, slice and integration tests?

Not the classic pyramid; I go by the nature of the service: with a lot of complex domain logic, more unit tests; with a "glue" service that mostly reads and writes the database and external APIs, more integration tests with Testcontainers. The criterion: which test catches a bug the cheapest and most reliably.

📖 Answer

The test pyramid says "many unit tests, few integration tests". But in a near-CRUD service, unit tests mostly check the mocks: was repo.save called? Yes. The real bugs are in SQL, in mapping, in transaction boundaries, in JSON serialization, and only a test with a real database sees those. That's why for such services the "test trophy" shape, with the integration layer the thickest, fits better.

I ask these questions when deciding:

  • Where is the domain logic? Price calculation, state machines, discount rules: pure Java, unit tests without Spring, with many parameterized cases.
  • How many integration points are there? At least one real test for every repository, every external client, every Kafka listener.
  • How fast does the feedback need to be? If a local mvn test goes over 1-2 minutes, developers stop running it.

The usual split in an average service comes out like this: unit tests of a few hundred milliseconds for the domain; a @WebMvcTest for each controller (validation, security, error formats); one @SpringBootTest + Testcontainers set with a single shared context for the main business flows; WireMock for external services.

I keep E2E tests (several services, UI) to a minimum: 5-10 "smoke" flows. They're slow, brittle, and finding the cause when they fail is expensive.

What matters isn't the numbers: if for each of the last 10 bugs that reached prod you answer "which test should have caught this", it becomes clear which layer is missing.