Sub topic 14
Testing the web layer with MockMvc
This chapter assumes you have the BookController, BookService, BookNotFoundException, and ApiExceptionHandler classes from the earlier chapters. It also assumes you know basic JUnit 5 and Mockito. You will write tests that check status codes and JSON without starting a server or a database.
What a slice test loads
A full @SpringBootTest starts the whole application context, including JPA and the database. That is slow, and it is more than you need to check HTTP behavior. @WebMvcTest is a slice test. It loads only the web layer: controllers, @RestControllerAdvice classes, JSON conversion, and validation. Services and repositories are not loaded, so you supply a mock for each dependency the controller needs.
MockMvc sends requests straight into Spring's DispatcherServlet without opening a network port. The request goes through the same routing, JSON conversion, validation, and exception handling as in production.
Writing the tests
The class below checks three behaviors: a missing book gives 404, a blank title gives 400, and a valid request gives 201 with a body and a Location header.
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.MockMvc;
@WebMvcTest(BookController.class)
class BookControllerTest {
@Autowired
private MockMvc mockMvc;
@MockitoBean
private BookService service;
@Test
void returnsNotFoundForUnknownBook() throws Exception {
when(service.get(1L)).thenThrow(new BookNotFoundException(1L));
mockMvc.perform(get("/api/books/1"))
.andExpect(status().isNotFound())
.andExpect(jsonPath("$.title").value("Book not found"));
}
@Test
void rejectsBlankTitle() throws Exception {
mockMvc.perform(post("/api/books")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"title\":\"\",\"author\":\"Ada\"}"))
.andExpect(status().isBadRequest());
}
@Test
void createsBook() throws Exception {
when(service.create(any(BookRequest.class)))
.thenReturn(new BookResponse(5L, "Notes", "Ada"));
mockMvc.perform(post("/api/books")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"title\":\"Notes\",\"author\":\"Ada\"}"))
.andExpect(status().isCreated())
.andExpect(header().string("Location", "http://localhost/api/books/5"))
.andExpect(jsonPath("$.id").value(5));
}
}Each test follows the same steps:
- Stub the mock with
when(...)for the case you want. - Call
mockMvc.perform(...)with the method, path, headers, and body. - Check the result with
andExpect, usingstatus(),header(), orjsonPath().
In the validation test, the service is never called. The @Valid annotation rejects the body before the controller method runs, so no stub is needed.
Common errors
@MockitoBeandoes not compile. It needs Spring Boot 3.4 or later. On older versions, use@MockBeanfromorg.springframework.boot.test.mock.mockito.NoSuchBeanDefinitionExceptionfor a service or repository. The controller depends on a bean the slice did not load. Add a@MockitoBeanfield for it.- A 404 where you expected 201, or the reverse. Check that the path in the test matches the
@RequestMappingand thatcontentTypeis set. Without it, a POST with a JSON body returns 415. - A mocked method returns
null. An unstubbed Mockito mock returnsnullor an empty value. Stub every call the controller makes on that path.
Exercise
A new test sends GET /api/books/7 to a controller whose service is mocked with @MockitoBean, but the test never stubs service.get(7L). The controller returns 200 with an empty body. Why does this happen, and how do you test the 404 case?
Show answer
An unstubbed Mockito mock returns null, so the controller returns null, which Spring writes as an empty 200 response. To test the 404 case, stub the call with when(service.get(7L)).thenThrow(new BookNotFoundException(7L)). ApiExceptionHandler then maps the exception to 404.