Testing Spring Boot Apps
Spring Boot projects come with JUnit 5, Mockito and AssertJ ready to use. Run all tests with ./mvnw test.
Spring Boot projects come ready to test at every level: fast plain unit tests, web-layer tests with MockMvc, repository tests with an in-memory database, and full application tests. Most tests should be the fast kind.
Plain unit tests: fastest
Example
class DeliveryServiceTest {
@Test
void freeDeliveryFromTheLimit() {
var service = new DeliveryService(new ShopSettings(18, 499, "support@example.com"));
assertThat(service.deliveryFee(499)).isEqualTo(0);
assertThat(service.deliveryFee(498)).isEqualTo(40);
}
}Because we used constructor injection, we can create the service with new - no Spring needed, and the test runs in milliseconds.
Testing a controller with MockMvc
Example
@WebMvcTest(ProductController.class) // starts only the web layer
class ProductControllerTest {
@Autowired MockMvc mvc;
@MockitoBean ProductRepository repo; // a fake repository (Spring Boot 3.4+)
@Test
void returnsProductAsJson() throws Exception {
when(repo.findById(1L)).thenReturn(Optional.of(new Product("Kettle", "kitchen", 1299, 5)));
mvc.perform(get("/api/products/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("Kettle"))
.andExpect(jsonPath("$.price").value(1299));
}
@Test
void unknownProductIs404() throws Exception {
when(repo.findById(9L)).thenReturn(Optional.empty());
mvc.perform(get("/api/products/9")).andExpect(status().isNotFound());
}
}Older Spring Boot versions use @MockBean instead of @MockitoBean.
Repository tests
Example
@DataJpaTest // starts JPA with an in-memory database
class ProductRepositoryTest {
@Autowired ProductRepository repo;
@Test
void findsByCategory() {
repo.save(new Product("Kettle", "kitchen", 1299, 5));
repo.save(new Product("Iron", "home", 899, 2));
assertThat(repo.findByCategory("kitchen")).extracting(Product::getName).containsExactly("Kettle");
}
}Full app tests
@SpringBootTest starts the whole app. Use it for a few end-to-end checks, and Testcontainers to test against a real PostgreSQL in Docker. Keep most tests small and fast.
Key points
- Constructor injection makes plain unit tests easy.
- @WebMvcTest tests controllers; @DataJpaTest tests repositories.
- Run tests with ./mvnw test.
📝 Test yourself
1. Which annotation starts only the web layer for controller tests?
2. Why can DeliveryService be tested without Spring?
3. Fill in the Maven command that runs tests:
./mvnw
