Sub topic 14
Testing controllers with @WebMvcTest and MockMvc
This chapter assumes you can write a @RestController with a service dependency, you know JUnit 5 basics, and you have spring-boot-starter-test on the test classpath. Spring Boot web projects include it by default when generated from Spring Initializr.
What a slice test does
A full @SpringBootTest starts the whole application context. That is slow, and it pulls in the database, the security setup and every bean. A controller test needs only the web layer: routing, argument binding, validation, JSON conversion and exception handlers.
@WebMvcTest loads that slice. It registers controllers, @RestControllerAdvice classes, Jackson and the MVC infrastructure. It does not register @Service, @Repository or @Component beans. Because of that, you supply the service as a mock.
MockMvc is a test client that sends a fake request through the DispatcherServlet without opening a network port. Because no real server runs, the tests are fast.
A first test
@WebMvcTest(BookController.class)
class BookControllerTest {
@Autowired
MockMvc mockMvc;
@MockitoBean
BookService service;
@Test
void returnsBookById() throws Exception {
when(service.get(1L)).thenReturn(new BookResponse(1L, "Dune", "Frank Herbert"));
mockMvc.perform(get("/api/books/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.title").value("Dune"));
}
}Each part has a job:
@WebMvcTest(BookController.class)limits the context to one controller. Without the argument, all controllers load.@MockitoBeanputs a Mockito mock into the context in place of the real service. It exists in Spring Boot 3.4 and later. In earlier versions, use@MockBean.when(...).thenReturn(...)defines what the mock returns.performsends the request.andExpectchecks the result.jsonPath("$.title")reads a field from the JSON body.$is the root.
The static imports come from MockMvcRequestBuilders, MockMvcResultMatchers, and org.mockito.Mockito.
Testing the unhappy paths
The happy path is only part of the contract. Validation and error handling are web-layer behavior, so test them here.
To send a body, set the content type and pass a JSON string:
@Test
void rejectsBlankTitle() throws Exception {
String json = """
{"title": "", "author": "Frank Herbert"}
""";
mockMvc.perform(post("/api/books")
.contentType(MediaType.APPLICATION_JSON)
.content(json))
.andExpect(status().isBadRequest());
verifyNoInteractions(service);
}
@Test
void returns404WhenBookIsMissing() throws Exception {
when(service.get(99L)).thenThrow(new BookNotFoundException(99L));
mockMvc.perform(get("/api/books/99"))
.andExpect(status().isNotFound())
.andExpect(jsonPath("$.title").value("Book not found"));
}The first test shows that @Valid stops the request before the service runs. verifyNoInteractions confirms that. The second test passes only because @WebMvcTest also loads ApiExceptionHandler, so the thrown exception becomes a ProblemDetail.
Common errors
| Symptom | Likely cause |
|---|---|
| `NoSuchBeanDefinitionException` for `BookService` | The service is not mocked. Add `@MockitoBean`. |
| 415 Unsupported Media Type | The request is missing `.contentType(MediaType.APPLICATION_JSON)`. |
| 200 or 404 with an empty body from a mock | The `when(...)` call does not match the arguments. A mock returns `null` or an empty collection by default. |
| 403 or 401 on every request | Spring Security is on the classpath. Configure the test user or security setup. |
Where this fits
Use @WebMvcTest for HTTP behavior: status codes, headers, JSON shape, validation and error mapping. Test business rules in plain unit tests of the service. Use @SpringBootTest for a few end-to-end checks that wire everything together.
Exercise
A test for POST /api/books with a valid JSON body returns 415. The body and the mock are correct. What is missing, and why does the failure happen before the controller runs?
Show answer
The request has no Content-Type: application/json header, so add .contentType(MediaType.APPLICATION_JSON) to the request builder. Spring MVC chooses a message converter from the content type. With no matching converter, it rejects the request with 415 before it calls the controller method.
Exercise
Write the assertions for a test where service.get(5L) returns new BookResponse(5L, "Emma", "Jane Austen"), checking the status and the author field.
Show answer
mockMvc.perform(get("/api/books/5")).andExpect(status().isOk()).andExpect(jsonPath("$.author").value("Jane Austen"));