Sub topic 8
Testing controllers with @WebMvcTest and MockMvc
This chapter assumes you can build a Spring Boot REST controller, you understand dependency injection, and you have written a JUnit 5 test. It also assumes you have read the chapters on test slices and on replacing beans with mocks.
What @WebMvcTest loads
@WebMvcTest is a test slice for the web layer. It starts a Spring context that contains only web components: controllers, @ControllerAdvice, JSON converters, filters, and WebMvcConfigurer beans. It does not load @Service, @Component, or @Repository beans, and it does not start a server.
Because the context is small, the test starts quickly. It also tests what a controller is responsible for: URL mapping, request parsing, status codes, and response bodies.
A first controller test
The controller depends on a GreetingService. The slice does not create that service, so the test must supply a replacement. @MockitoBean registers a Mockito mock in the context. In Spring Boot versions before 3.4, use @MockBean instead.
@WebMvcTest(GreetingController.class)
class GreetingControllerTest {
@Autowired
MockMvc mockMvc;
@MockitoBean
GreetingService service;
@Test
void returnsGreeting() throws Exception {
when(service.greetingFor("Ada")).thenReturn("Hello, Ada");
mockMvc.perform(get("/greetings/Ada"))
.andExpect(status().isOk())
.andExpect(content().string("Hello, Ada"));
}
}The test has four parts:
@WebMvcTest(GreetingController.class)limits the context to one controller. Without the argument, Spring loads every controller it finds.MockMvcis auto-configured and injected. It sends requests straight into Spring'sDispatcherServletwithout opening a network port.when(...).thenReturn(...)sets up what the mock service returns.perform(...)sends the request, andandExpect(...)checks the response.
The static imports come from MockMvcRequestBuilders (get), MockMvcResultMatchers (status, content), and Mockito (when).
How a request flows
Everything between MockMvc and the mock service is real Spring MVC code. Routing, argument binding, validation, and JSON conversion all run as they would in production.
Checking what matters
Match the assertions to what the controller does. A status check alone proves little. Check the body, headers, and error cases too.
| Concern | Typical assertion |
|---|---|
| Status code | `status().isNotFound()` |
| Plain text body | `content().string("Hello, Ada")` |
| JSON field | `jsonPath("$.name").value("Ada")` |
| Header | `header().string("Location", "/greetings/1")` |
| Content type | `content().contentType(MediaType.APPLICATION_JSON)` |
To test a POST, set the content type and body on the request builder:
mockMvc.perform(post("/greetings")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"name\":\"Ada\"}"))
.andExpect(status().isCreated());Common errors
NoSuchBeanDefinitionExceptionfor a service or repository. The controller needs a bean the slice does not load. Add a@MockitoBeanfor it.- A mock returns
nullor an empty value. An unstubbed mock method returns a default value. Add awhen(...)for the call your controller makes. - A 404 you did not expect. The path or HTTP method in the test does not match the mapping. Check both.
- A 401 or 403 you did not expect. Spring Security is on the classpath and secures the endpoint. A later chapter covers the security test support.
Exercise
A controller calls OrderService. You write a @WebMvcTest for it and the context fails to start with a missing OrderService bean. What do you add to the test class, and why?
Show answer
Add a field annotated with @MockitoBean (or @MockBean before Spring Boot 3.4) of type OrderService. The web slice does not load @Service beans, so the controller has no OrderService to inject until the test registers a mock.
Exercise
Write the andExpect call that checks a JSON response has a name field equal to "Ada".
Show answer
.andExpect(jsonPath("$.name").value("Ada"))