Concept Explanation
Unit tests prove a class works in isolation. They cannot prove your JSON mapping is right, your SQL is valid, or your security rules apply. For that you need to start (part of) the real application.
Spring Boot gives you three levels, from cheap to expensive:
| Annotation | Starts | Speed |
|---|---|---|
@WebMvcTest | web layer only, services mocked | fast |
@DataJpaTest | JPA + in-memory database | fast |
@SpringBootTest | the whole application | slow |
Testing a Controller Alone
@WebMvcTest(ProductController.class)
class ProductControllerTest {
@Autowired MockMvc mvc;
@MockBean ProductService service; // the real service is replaced
@Test
void returnsProductAsJson() throws Exception {
when(service.byId(1L)).thenReturn(new Product(1L, "Pen"));
mvc.perform(get("/api/products/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("Pen"));
}
@Test
void rejectsInvalidBody() throws Exception {
mvc.perform(post("/api/products")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"name\":\"\"}"))
.andExpect(status().isBadRequest());
}
}
No server socket is opened, but routing, JSON serialisation, and validation are all genuinely exercised.
Testing Repositories
@DataJpaTest
class ProductRepositoryTest {
@Autowired ProductRepository repo;
@Test
void findsByNameFragment() {
repo.save(new Product("Blue Pen"));
repo.save(new Product("Red Book"));
List<Product> found = repo.findByNameContainingIgnoreCase("pen");
assertEquals(1, found.size());
}
}
Each test runs in a transaction that is rolled back afterwards, so tests cannot pollute each other.
The Full Application
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class ProductApiIT {
@Autowired TestRestTemplate rest;
@Test
void createThenFetch() {
ResponseEntity<Product> created = rest.postForEntity(
"/api/products", new CreateProductRequest("Lamp", TEN), Product.class);
assertEquals(HttpStatus.CREATED, created.getStatusCode());
Product fetched = rest.getForObject(
"/api/products/" + created.getBody().getId(), Product.class);
assertEquals("Lamp", fetched.getName());
}
}
Real Databases with Testcontainers
An in-memory H2 database does not behave like production PostgreSQL. Testcontainers runs the real thing in Docker:
@SpringBootTest
@Testcontainers
class RealDbIT {
@Container
static PostgreSQLContainer<?> db =
new PostgreSQLContainer<>("postgres:16");
@DynamicPropertySource
static void props(DynamicPropertyRegistry r) {
r.add("spring.datasource.url", db::getJdbcUrl);
r.add("spring.datasource.username", db::getUsername);
r.add("spring.datasource.password", db::getPassword);
}
}
Common Mistakes
@SpringBootTestfor everything: Starting the full context per test class turns a 5-second suite into 5 minutes. Use the narrowest slice.- Tests that depend on order: Each test must set up its own data and assume nothing.
- Hitting real external APIs: Your suite then fails when someone else's server is down. Use WireMock.
- H2 in tests, PostgreSQL in production: Dialect differences hide real bugs until deployment.
Best Practices
- Shape the suite like a pyramid: many unit tests, some slice tests, a few end-to-end tests.
- Name integration tests
*ITso the build can run them in a separate, slower phase. - Assert on status codes and JSON structure, not on log output.
- Use
@ActiveProfiles("test")to keep test configuration clearly separate.
Practice Exercises
- The Slice: Write a
@WebMvcTestthat asserts a 400 response for an invalid request body, with the service mocked out. - The Rollback: Save a row in a
@DataJpaTest, then confirm in a second test that the row is gone. - The Round Trip: Use
@SpringBootTestwithTestRestTemplateto POST then GET the same resource.