Sub topic 8
Testing controllers with @WebMvcTest and MockMvc
This chapter assumes you can write a Spring MVC controller, you know what a Spring bean is, and you have already written plain unit tests with JUnit 5 and Mockito. It builds on the earlier chapters about test slices and about replacing beans with mocks.
What @WebMvcTest loads
A controller does more than run Java code. It maps URLs to methods, converts JSON into objects, validates input, and turns exceptions into HTTP status codes. A plain unit test that calls the controller method directly skips all of that. A full @SpringBootTest covers it, but it also starts your services, repositories, and database.
@WebMvcTest sits between the two. It starts a Spring context that contains only the web layer:
- Classes annotated with
@Controller,@RestController, and@ControllerAdvice. @JsonComponentbeans,ConverterandFilterbeans, andWebMvcConfigurerimplementations.- The Spring MVC infrastructure, including Jackson for JSON.
- A
MockMvcbean that you can inject into the test.
It does not load @Service, @Component, or @Repository beans. If your controller needs a service, you must supply one, usually as a mock.
A first controller test
Assume this controller exists. It is the one tested in the example below.
@RestController
class GreetingController {
private final GreetingService service;
GreetingController(GreetingService service) {
this.service = service;
}
@GetMapping("/greetings/{name}")
String greet(@PathVariable String name) {
return service.greetingFor(name);
}
}The test loads only this controller and replaces its service:
@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"));
}
}Several things happen here:
@WebMvcTest(GreetingController.class)limits the context to that one controller plus the shared web infrastructure. Without the argument, every controller in the application is loaded, and each of them needs its dependencies satisfied.@MockitoBeanregisters a Mockito mock as a bean in the context. The controller receives it through constructor injection. In Spring Boot versions before 3.4, use@MockBeaninstead. The behavior is the same.mockMvc.perform(...)sends a simulated request through theDispatcherServlet. No real server starts and no network port opens, so the test runs quickly.- The
andExpectcalls check the response.
The static imports come from MockMvcRequestBuilders (get, post), MockMvcResultMatchers (status, content, jsonPath), and Mockito and AssertJ as in earlier chapters.
Reading the request and response API
MockMvc has a builder style. You describe a request, perform it, then chain expectations.
| Part | Examples | Purpose |
|---|---|---|
| Request builder | `get(url)`, `post(url)`, `put`, `delete` | Chooses the method and URL |
| Request options | `.param("q", "x")`, `.header("X-Id", "1")`, `.contentType(...)`, `.content(json)`, `.accept(...)` | Adds query parameters, headers, and a body |
| Status matchers | `status().isOk()`, `isCreated()`, `isBadRequest()`, `isNotFound()` | Checks the HTTP status |
| Body matchers | `content().string(...)`, `content().json(...)`, `jsonPath("$.name").value("Ada")` | Checks the response body |
| Header matchers | `header().string("Location", ...)` | Checks response headers |
| Debugging | `.andDo(print())` | Prints the full request and response to the console |
When a test fails and the reason is unclear, add .andDo(print()) after perform. It shows the status, headers, resolved handler, and any exception, which usually points directly at the problem.
Testing JSON input and validation
Most real controllers accept JSON and validate it. Consider this endpoint:
record CreateGreetingRequest(@NotBlank String name, @NotBlank String message) {}
@PostMapping("/greetings")
ResponseEntity<Void> create(@Valid @RequestBody CreateGreetingRequest request) {
service.create(request.name(), request.message());
return ResponseEntity.created(URI.create("/greetings/" + request.name())).build();
}Add these tests to the same test class:
@Test
void createsGreeting() throws Exception {
mockMvc.perform(post("/greetings")
.contentType(MediaType.APPLICATION_JSON)
.content("""
{"name": "Ada", "message": "Hello, Ada"}
"""))
.andExpect(status().isCreated())
.andExpect(header().string("Location", "/greetings/Ada"));
verify(service).create("Ada", "Hello, Ada");
}
@Test
void rejectsBlankName() throws Exception {
mockMvc.perform(post("/greetings")
.contentType(MediaType.APPLICATION_JSON)
.content("""
{"name": "", "message": "Hello"}
"""))
.andExpect(status().isBadRequest());
verifyNoInteractions(service);
}The second test is a reason to prefer this slice. The @Valid annotation only works when Spring MVC processes the request, so a direct method call would never trigger it. verifyNoInteractions(service) confirms that a rejected request never reaches the service.
To check fields in a JSON response, use jsonPath:
mockMvc.perform(get("/greetings/Ada/details"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("Ada"))
.andExpect(jsonPath("$.message").value("Hello, Ada"));Use content().json(expected) to compare a whole document. It ignores extra fields and field order by default, which keeps tests from breaking on harmless changes.
Testing error handling
If the service throws an exception, you can check how the web layer reports it. Suppose GreetingNotFoundException is mapped to 404 by a @ControllerAdvice class or by @ResponseStatus:
@Test
void returnsNotFoundWhenGreetingIsMissing() throws Exception {
when(service.greetingFor("Bob")).thenThrow(new GreetingNotFoundException("Bob"));
mockMvc.perform(get("/greetings/Bob"))
.andExpect(status().isNotFound());
}Because @WebMvcTest loads @ControllerAdvice beans, this test exercises the real exception mapping. If the status you get is 500 and you expected 404, the advice class is usually missing or the exception type does not match.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `NoSuchBeanDefinitionException` for a service or repository | The controller depends on a bean the slice does not load | Add a `@MockitoBean` for that type |
| Every request returns 404 | The controller was not loaded, or the URL differs from the mapping | Check the class named in `@WebMvcTest` and the path |
| Request returns 401 or 403 when security is on the classpath | Spring Security is active in the slice and the request is not authenticated | Add test security support, covered in a later chapter |
| POST or PUT returns 403 with no obvious reason | CSRF protection rejects requests without a token | Use the security test helpers rather than disabling CSRF |
| Mock returns `null` or an empty value | The stubbed arguments do not match the real call | Check argument values, or use matchers such as `eq()` and `any()` |
| Test starts a database or fails on JPA configuration | `@EnableJpaRepositories` or similar sits on the main application class | Move that configuration to its own `@Configuration` class |
The last row deserves a closer look. @WebMvcTest finds your @SpringBootApplication class and uses it as its configuration. Any annotation on that class, such as @EnableJpaRepositories or @EnableScheduling, then applies to every slice test. Put those annotations on separate configuration classes so slices can ignore them.
Matcher mistakes with Mockito
When you stub a method with a matcher, every argument must use a matcher. Mixing raw values and matchers causes an InvalidUseOfMatchersException:
// Wrong: mixes a matcher and a raw value
when(service.find(any(), "Ada")).thenReturn(result);
// Right: matchers for all arguments
when(service.find(any(), eq("Ada"))).thenReturn(result);When to choose @WebMvcTest
Use it for anything that belongs to the HTTP contract: routes, status codes, JSON shape, validation, content negotiation, and exception mapping. Do not use it to test business rules. Those belong in service unit tests, where setup is cheaper and failures point to the logic itself.
Exercise
A @WebMvcTest(OrderController.class) test fails at startup with NoSuchBeanDefinitionException: No qualifying bean of type 'OrderService'. Why does this happen, and what is the smallest fix?
Show answer
The web slice loads only controllers and web infrastructure, not @Service beans, so OrderController cannot get its OrderService. Add a field @MockitoBean OrderService orderService; (or @MockBean before Spring Boot 3.4) to the test class so the context contains a mock of that type.
Exercise
You want a test showing that a POST with a blank name field is rejected and the service is never called. Which MockMvc expectation and which Mockito call do you use?
Show answer
Use .andExpect(status().isBadRequest()) after performing the POST with a JSON body containing a blank name, and then call verifyNoInteractions(service). This only works if the request body parameter is annotated with @Valid.