Spring Boot Testing Mastery
Testing is what separates “demo code” from production code. Spring has a powerful testing framework.1. The Test Pyramid
- Unit Tests: Test a single class in isolation. Use Mocks.
- Integration Tests: Test multiple components together (e.g., Controller + Service + DB).
- E2E Tests: Full system test (Browser automation, etc.).
2. Unit Testing with JUnit 5 & Mockito
No Spring context. Pure Java testing.@Mock: Create a mock object.when(...).thenReturn(...): Define mock behavior.verify(...): Assert that a method was called.- AssertJ (
assertThat): Fluent assertions (better than JUnit’sassertEquals).
3. Slice Testing (@WebMvcTest, @DataJpaTest)
Spring Boot provides Test Slices that load ONLY the relevant parts of the context.@WebMvcTest (Controller Layer)
MockMvc: Simulates HTTP calls without starting the server.@MockBean: Replaces a real bean with a mock in the test context.
@DataJpaTest (Repository Layer)
4. Integration Testing (@SpringBootTest)
Loads the full application context. Closest to production.5. Testcontainers (Real Databases)
H2 is convenient, but it’s NOT PostgreSQL. Differences in SQL dialects can cause bugs. Testcontainers spins up a real Postgres container via Docker.Dependency
Usage
6. Mocking External APIs (WireMock)
If your service calls an external HTTP API, you don’t want to hit the real API in tests.7. Best Practices
- Don’t overuse
@SpringBootTest: It’s slow. Use slices (@WebMvcTest,@DataJpaTest) when possible. - Use Testcontainers for DB tests: H2 is good for unit tests, but integration tests should use the real DB.
- Test behavior, not implementation: Don’t test private methods.
- Avoid
Thread.sleep()in tests: UseAwaitilityfor async assertions.