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 type | Annotation | Loads | Use for |
|---|---|---|---|
| Unit | none (JUnit + Mockito) | nothing | Service logic, fast and many |
| Web slice | @WebMvcTest(OrderController.class) | MVC layer only | Status codes, JSON, validation, error handling |
| Data slice | @DataJpaTest | JPA and repositories | Queries and mappings |
| Full | @SpringBootTest | Whole application context | A 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)
- Spring Boot reference: Testing Spring Boot applicationsdocs.spring.io