Video in progress

Junior 🌱 Spring

How do you test a controller endpoint with MockMvc?

@WebMvcTest brings up only the web layer, and MockMvc sends an HTTP request without opening a server, with the service mocked. Then you check the status, headers and the JSON body.

📖 Answer

@WebMvcTest(BookController.class)
class BookControllerTest {

    @Autowired MockMvc mvc;
    @MockitoBean BookService service;   // up to Boot 3.4: @MockBean

    @Test
    void returnsBook() throws Exception {
        when(service.find(1L)).thenReturn(new BookDto(1L, "O'tkan kunlar"));

        mvc.perform(get("/api/books/1").accept(MediaType.APPLICATION_JSON))
           .andExpect(status().isOk())
           .andExpect(jsonPath("$.title").value("O'tkan kunlar"));
    }

    @Test
    void rejectsEmptyTitle() throws Exception {
        mvc.perform(post("/api/books")
                .contentType(MediaType.APPLICATION_JSON)
                .content("{\"title\":\"\"}"))
           .andExpect(status().isBadRequest());
    }
}

This test covers URL mapping, JSON serialization, validation and the error responses in @ControllerAdvice. It all goes through the real Spring MVC, just without the network. The service logic and the database aren't tested; they're mocked.

If Spring Security is on the classpath, the request may return 401, and then you need @WithMockUser. Spring Framework 6.2 also added an AssertJ-style MockMvcTester, so you can write new tests with it.