Skip to content
Ameen Abozaid
Planned lessonJNR-016-L04

@WebMvcTest and MockMvc

  • Lesson 4 of 7
  • Junior
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 (@MockitoBean in recent Spring, @MockBean in older; verify version before recording).
  • MockMvc sends 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

java
@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.

Lab and exercises Quiz

Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.

Continue to next lesson

Type to search levels, phases, modules and lessons.