Sub topic 14
Testing controllers with @WebMvcTest and MockMvc
This chapter assumes you have read the earlier chapters of this tutorial. You should know BookController, BookService, the record DTOs, ApiExceptionHandler, and basic JUnit 5 and Mockito usage. The examples use Spring Boot 3.4 or later and the spring-boot-starter-test dependency.
What a slice test loads
A controller does three jobs that plain unit tests can't check. It maps URLs to methods, converts JSON to objects and back, and turns exceptions into HTTP responses. A plain unit test that calls controller.get(1) skips all three. A @SpringBootTest covers them, but it starts the whole application, including the database and every bean.
@WebMvcTest sits between the two. It builds a Spring context with only the web layer:
- Included:
@Controllerand@RestControllerbeans,@RestControllerAdvice, Jackson'sObjectMapper, message converters, validation, andMockMvc. - Excluded:
@Service,@Componentand@Repositorybeans, and anything else outside the web layer.
Because services are excluded, a controller that needs BookService can't start unless the test supplies one. You supply a Mockito mock, so the test checks only the controller.
MockMvc calls Spring's DispatcherServlet directly. No server starts and no port opens. Each request is a Java method call, so tests run fast, but they also can't catch problems that only exist in a real servlet container.
A first test, with imports
The spine example omits imports. Here is the same test as a complete file, with one extra check for the 404 path.
package com.example.books;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
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
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"));
}
@Test
void returnsProblemDetailWhenBookIsMissing() throws Exception {
when(service.get(99L)).thenThrow(new BookNotFoundException(99L));
mockMvc.perform(get("/api/books/99"))
.andExpect(status().isNotFound())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.title").value("Book not found"))
.andExpect(jsonPath("$.detail").value("No book with id 99"));
}
}The second test exercises ApiExceptionHandler without any extra setup. @WebMvcTest includes @RestControllerAdvice beans, so the mocked service throws the domain exception and the real handler converts it. This is the main reason to prefer a slice test over a unit test.
A request goes through three steps:
perform(...)runs the request and returns aResultActionsobject.andExpect(...)runs one assertion. It throws if the assertion fails, so the first failed assertion stops the test.andDo(print())prints the full request and response to the console. Add it while you debug a failing test.
Testing the request path
Query parameter defaults are easy to break and easy to test. The controller declares @RequestParam(defaultValue = ""), so a request with no title should call search("").
@Test
void listUsesEmptyTitleByDefault() throws Exception {
when(service.search("")).thenReturn(List.of(new BookResponse(1L, "Dune", "Frank Herbert")));
mockMvc.perform(get("/api/books"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.length()").value(1))
.andExpect(jsonPath("$[0].author").value("Frank Herbert"));
}
@Test
void listPassesTitleFilter() throws Exception {
when(service.search("dune")).thenReturn(List.of());
mockMvc.perform(get("/api/books").param("title", "dune"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.length()").value(0));
}If the mock isn't stubbed for the exact arguments, Mockito returns its default. For a List that is an empty list, so a wrong argument can silently produce an empty result. Use verify(service).search("dune") when the argument itself is what you want to check.
Testing POST: body, 201 and Location
For POST requests the test must send JSON and set the Content-Type header. Without it, Spring answers 415 (Unsupported Media Type) and the controller never runs.
@Test
void createReturns201WithLocation() throws Exception {
CreateBookRequest request = new CreateBookRequest("Dune", "Frank Herbert");
when(service.create(request)).thenReturn(new BookResponse(5L, "Dune", "Frank Herbert"));
mockMvc.perform(post("/api/books")
.contentType(MediaType.APPLICATION_JSON)
.content("""
{"title": "Dune", "author": "Frank Herbert"}
"""))
.andExpect(status().isCreated())
.andExpect(header().string("Location", "http://localhost/api/books/5"))
.andExpect(jsonPath("$.id").value(5));
}The stub when(service.create(request)) matches because Java records implement equals by component values. The deserialized body equals the request object, so Mockito treats the argument as a match. With a regular class you would need to implement equals or use an ArgumentMatcher.
MockMvc requests default to host localhost and no port, so ServletUriComponentsBuilder.fromCurrentRequest() produces http://localhost/api/books/5. If you assert on the whole URL, expect that form. To check only the path, use header().string("Location", endsWith("/api/books/5")) with the Hamcrest endsWith matcher.
Testing validation
Validation tests answer one question: does bad input stop at the controller? Send a blank title and check two things, the status and that the service was never called.
@Test
void createRejectsBlankTitle() throws Exception {
mockMvc.perform(post("/api/books")
.contentType(MediaType.APPLICATION_JSON)
.content("""
{"title": " ", "author": "Frank Herbert"}
"""))
.andExpect(status().isBadRequest());
verify(service, never()).create(any());
}The never() check matters. A test that checks only the status would still pass if validation ran after the service call, which is a real bug. Add a test per constraint, for example a 201-character title for @Size(max = 200).
The response body depends on configuration. With spring.mvc.problemdetails.enabled=true in application.properties, the 400 body is a ProblemDetail, and @WebMvcTest reads that file. Without the property, the body is not a problem document, and MockMvc does not run Boot's error page. In both cases status().isBadRequest() is reliable. Assert on the body only when your API promises a format.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `UnsatisfiedDependencyException` or `NoSuchBeanDefinitionException` for `BookService` | The slice does not load services | Add `@MockitoBean BookService service;` to the test |
| 415 instead of 201 | No `contentType` on the request | Add `.contentType(MediaType.APPLICATION_JSON)` |
| 400 on a body you thought was valid | JSON field names differ from the record components, or the JSON is malformed | Compare field names, and use `andDo(print())` |
| 401 or 403 on every request | Spring Security is on the classpath, and the slice includes its configuration | Use `@WithMockUser`, and add `.with(csrf())` to POST, PUT and DELETE requests |
| `@MockBean` shows a deprecation warning | `@MockBean` is deprecated since Spring Boot 3.4 | Use `@MockitoBean` from `org.springframework.test.context.bean.override.mockito` |
| Test passes but search returns nothing useful | The mock was stubbed with different arguments, so Mockito returned its default | Add `verify(...)` on the arguments |
Choosing the right kind of test
- Use
@WebMvcTestfor mappings, binding, validation, status codes, headers, JSON shape and exception handlers. - Use a plain unit test for service logic. It needs no Spring at all.
- Use
@SpringBootTestwith@AutoConfigureMockMvcfor a few end-to-end checks of the whole stack, such as real wiring between controller, service and database.
Exercise
A test for POST /api/books with a valid JSON body returns 415 instead of 201. The controller code is correct. What is missing from the test, and why does the controller method never run?
Show answer
The request has no Content-Type: application/json header, which you set with .contentType(MediaType.APPLICATION_JSON). Spring picks a message converter for @RequestBody from that header. With no matching converter it rejects the request with 415 before the controller method is called.
Exercise
Write the assertion lines for a test that expects GET /api/books/99 to return a 404 problem document when service.get(99L) throws BookNotFoundException. Why does the test work even though it never references ApiExceptionHandler?
Show answer
Use .andExpect(status().isNotFound()) and .andExpect(jsonPath("$.title").value("Book not found")). It works because @WebMvcTest loads @RestControllerAdvice beans along with the controllers, so the real handler converts the exception thrown by the mocked service.