@WebMvcTest and MockMvc
On This Lesson 4 topics
This lesson is planned. The outline below lists the topics it will cover. The full lesson has not been published yet.
In this lesson
test a controller through HTTP without starting a server.
Planned topics
@WebMvcTest(ProductController.class)loads only the web layer (controller, advice, JSON), not services or repositories.- Provide the service as a mock bean (
@MockitoBeanin recent Spring,@MockBeanin older; verify version before recording). MockMvcsends fake requests and checks status, JSON, and headers.- Test success, validation failure (400), and not found (404), and check the body, not only the status.
Draft outline details
Demonstration
@WebMvcTest(ProductController.class)
class ProductControllerTest {
@Autowired MockMvc mvc;
@MockitoBean ProductService service;
@Test void notFound() throws Exception {
when(service.get(9)).thenThrow(new NotFoundException("Product", 9));
mvc.perform(get("/products/9"))
.andExpect(status().isNotFound())
.andExpect(jsonPath("$.detail").value("Product 9 not found"));
}
}Check your understanding
What does @WebMvcTest not load?
Show answer
Services, repositories, and the rest of the app.
Practice
Apply this lesson with the module's lab, exercises and quiz.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.