How do you test a Spring Boot service with confidence and speed?
BackendMid-level
In shortMostly fast unit tests for domain logic, slice tests for the web and persistence layers, a smaller set of integration tests against real dependencies with Testcontainers, and contract tests between services, all running in CI on every change.
Model answer
Unit tests (most of them): domain logic and services with plain constructors and fakes: no Spring context, milliseconds each. This is where business rules, edge cases and error paths are covered.
Slice tests:
@WebMvcTest: controllers with MockMvc: request mapping, validation, status codes, error format, security rules.@DataJpaTestwith Testcontainers PostgreSQL (not H2): queries, mappings, constraints, migrations. In-memory databases differ in SQL dialect, locking and constraint behavior, so they pass tests that production fails.
Integration tests (fewer): @SpringBootTest with real dependencies in containers (database, Kafka, Redis) for the critical flows end to end, plus WireMock for third-party HTTP APIs.
Contract tests: consumer-driven contracts (Pact or Spring Cloud Contract) or OpenAPI-based checks keep services and mobile clients compatible without deploying everything together.
Speed: Spring caches application contexts between tests with the same configuration, so avoid needless @MockitoBean variations and @DirtiesContext; reuse containers across tests; run unit tests on every commit and the full suite in CI.
What not to test: framework behavior (that Spring Data saves an entity), getters and setters, or private methods directly. Test behavior through public APIs.
What they're looking for
A layered strategy with reasons, Spring test slices (@WebMvcTest, @DataJpaTest), Testcontainers over in-memory databases, context caching for speed, contract tests, and what not to test.
Common mistakes
- Testing persistence against H2 while production runs PostgreSQL.
- @SpringBootTest for everything, making the suite slow.
- Mocking the database layer in tests meant to verify queries.
More backend questions
- What is the N+1 query problem, and how do you find and fix it?Mid-level
- What does Spring Boot's auto-configuration do, and how do you change what it set up?Mid-level
- How does a Spring backend authenticate requests from a mobile app, and how do you make sure users only see their own data?Mid-level
- Your Spring Boot service in Kubernetes keeps restarting with exit code 137. How do you investigate and fix it?Senior