Why this matters
- Full
@SpringBootTestloads every bean, every auto-configuration, and every external client — a suite of two hundred integration tests can take minutes. @WebMvcTestloads just the web layer; you verify HTTP status codes, JSON shapes, and validation without a database.@DataJpaTestloads JPA and an in-memory database; you verify query methods and entity mappings in isolation.
Slice tests
L1 · Fresher@WebMvcTest loads only MVC slices; @DataJpaTest loads JPA with an in-memory DB — faster than full context.
MockMvc
L2 · IntermediateCall endpoints without a real server; assert status, JSON body, and headers for BookStore controllers.
@MockBean
L3 · AdvancedReplace collaborators in the slice context — distinguish @Mock (JUnit) from @MockBean (Spring test context).
Test pyramid
L4 · ExpertMany fast slice/unit tests, fewer full integration tests — slice tests catch mapping bugs cheaply.
Test annotations and tools
@WebMvcTest— loads@Controllerbeans and MockMvc; auto-configures JSON serializers.@DataJpaTest— loads@Entityclasses and@Repositoryinterfaces with an embedded database.@MockBean— replaces a Spring bean with a Mockito mock inside the test context.MockMvc— sends fake HTTP requests and asserts on status, headers, and response body.@JsonTest— tests JSON serialization/deserialization of DTOs without any web layer.
Controller slice test
// learn:fragment
@WebMvcTest(BookController.class)
class BookControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private BookService bookService;
@Test
void getBook_returns200WithBody() throws Exception {
BookDetail detail = new BookDetail("978-0134685991", "Effective Java", "Joshua Bloch", 45.99);
when(bookService.getByIsbn("978-0134685991")).thenReturn(detail);
mockMvc.perform(get("/api/books/978-0134685991"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.title").value("Effective Java"))
.andExpect(jsonPath("$.price").value(45.99));
}
@Test
void getBook_returns404WhenMissing() throws Exception {
when(bookService.getByIsbn("unknown"))
.thenThrow(new BookNotFoundException("unknown"));
mockMvc.perform(get("/api/books/unknown"))
.andExpect(status().isNotFound())
.andExpect(jsonPath("$.title").value("Book Not Found"));
}
}
The rest of this guide is part of Pro
Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.
Still to come · 3 sections
- Validation and request body tests
- Repository slice test
- Pure unit test for service logic
Test yourself
Answer these before moving on — recall is what makes it stick.