Testing slices: @WebMvcTest vs @SpringBootTest
Pick the smallest harness that proves the thing
Spring offers several test slice annotations that load a narrow context. Use the narrowest slice that actually exercises the behavior you are testing — broader slices are slower, more flaky, and obscure the unit under test.
@WebMvcTest: load only the MVC layer. InjectMockMvc; mock services.@DataJpaTest: load JPA + an in-memory DB; test repositories and queries.@SpringBootTest: full context. Good for end-to-end smoke tests; slow.
@WebMvcTest(InvoiceController.class)
class InvoiceControllerTest {
@Autowired MockMvc mvc;
@MockBean InvoiceService service;
@Test
void returns_404_for_unknown_invoice() throws Exception {
when(service.load(99L)).thenThrow(new InvoiceNotFoundException(99L));
mvc.perform(get("/api/invoices/99"))
.andExpect(status().isNotFound());
}
}Takeaways
- Slice tests keep feedback fast and failures pinpointable.
- Full-context tests are good for smoke tests; keep them few.
- Testing private implementation detail is a smell — test public behavior.
Enjoying This Lesson?
Your support helps create more comprehensive courses and lessons like this one. Help me build better learning experiences for everyone.
Support Awashyak