Easy java spring

How do you test a Spring Boot application?

The 30 second answer

Most tests are plain unit tests: I create the service with its constructor and pass mocks, with no Spring at all. For the web layer I use @WebMvcTest with MockMvc, which loads only the controllers and checks status codes, JSON and validation. @DataJpaTest tests repositories against a database. @SpringBootTest starts the whole context for a few end-to-end tests, ideally with Testcontainers for a real database.

<!-- level: 1 -->

Test typeAnnotationLoadsUse for
Unitnone (JUnit + Mockito)nothingService logic, fast and many
Web slice@WebMvcTest(OrderController.class)MVC layer onlyStatus codes, JSON, validation, error handling
Data slice@DataJpaTestJPA and repositoriesQueries and mappings
Full@SpringBootTestWhole application contextA few end-to-end flows
@WebMvcTest(OrderController.class)
class OrderControllerTest {
    @Autowired MockMvc mvc;
    @MockitoBean OrderService orders;

    @Test
    void returns404WhenMissing() throws Exception {
        when(orders.find(42)).thenThrow(new OrderNotFoundException(42));
        mvc.perform(get("/api/orders/42")).andExpect(status().isNotFound());
    }
}
  • Spring Boot's test slices load only the part of the app a test needs, so they start fast.
  • @MockitoBean (Spring Framework 6.2 and later; older code uses @MockBean) replaces a bean in the test context with a Mockito mock.
  • For real database behaviour, Spring Boot supports Testcontainers so tests run against the same database engine as production instead of an in-memory substitute.
Sources (1)
  1. Spring Boot reference: Testing Spring Boot applicationsdocs.spring.io