How to Test Spring Controllers With MockMvc Step by Step
Test Spring MVC controllers with MockMvc and WebMvcTest: status, JSON, validation, security, uploads and exception handlers without a server.

A controller has little logic and a great deal of configuration: a path, a verb, how the body is read, which status comes back, what happens on an exception. The configuration is where controllers break, and a unit test that calls the method directly proves none of it. MockMvc tests the real thing. It sends a request through the actual DispatcherServlet, handler mappings, argument resolvers, validators, message converters and exception handlers, in the same process as the test, without opening a port. This post builds a test class for an orders controller step by step: the happy path, JSON assertions, request bodies, validation errors, exception handling, security and file uploads, then explains how to keep the suite fast and when to add a full integration test. For writing the controller side, see writing a Spring MVC REST controller.
The controller under test
@RestController
@RequestMapping("/api/orders")
public class OrderController {
private final OrderService orders;
public OrderController(OrderService orders) {
this.orders = orders;
}
@GetMapping("/{id}")
public OrderResponse get(@PathVariable long id) {
return orders.find(id).orElseThrow(() -> new OrderNotFoundException(id));
}
@PostMapping
public ResponseEntity<OrderResponse> create(@Valid @RequestBody CreateOrderRequest request) {
OrderResponse created = orders.create(request);
return ResponseEntity.created(URI.create("/api/orders/" + created.id())).body(created);
}
}
public record CreateOrderRequest(@NotBlank String customerEmail, @Positive int quantity) {}
public record OrderResponse(long id, String customerEmail, int quantity, String status) {}@RestControllerAdvice
class ApiExceptionHandler {
@ExceptionHandler(OrderNotFoundException.class)
ProblemDetail notFound(OrderNotFoundException e) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, e.getMessage());
problem.setTitle("Order not found");
return problem;
}
}The slice: @WebMvcTest
@WebMvcTest(OrderController.class) starts a Spring context containing only web components: the named controller, @ControllerAdvice classes, converters, filters and WebMvcConfigurer beans. Services and repositories are not loaded, so you provide the controller's collaborators as mocks, with @MockitoBean:
@WebMvcTest(OrderController.class)
class OrderControllerTest {
@Autowired
MockMvc mvc;
@MockitoBean
OrderService orders;
@Test
void returnsAnExistingOrderAsJson() throws Exception {
when(orders.find(7L)).thenReturn(Optional.of(new OrderResponse(7, "[email protected]", 2, "NEW")));
mvc.perform(get("/api/orders/7").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.id").value(7))
.andExpect(jsonPath("$.customerEmail").value("[email protected]"))
.andExpect(jsonPath("$.status").value("NEW"));
}
}mvc.perform(...) builds and executes a request; andExpect checks the result. The static imports come from MockMvcRequestBuilders (get, post, put, delete, multipart) and MockMvcResultMatchers (status, content, jsonPath, header). jsonPath uses JSONPath expressions: $ is the root, $.items[0].sku an element. Assert on the contract the client sees, which is the JSON, and avoid asserting on Java objects, since an object can look right while the serialisation is wrong, for example a date written as an array.
When the first assertion fails, the failure message prints the request and response if you add .andDo(print()), a debugging aid worth remembering:
mvc.perform(get("/api/orders/7")).andDo(print()).andExpect(status().isOk());MockHttpServletRequest:
HTTP Method = GET
Request URI = /api/orders/7
Handler:
Type = dev.javahacks.orders.OrderController
Method = dev.javahacks.orders.OrderController#get(long)
MockHttpServletResponse:
Status = 200
Content type = application/json
Body = {"id":7,"customerEmail":"[email protected]","quantity":2,"status":"NEW"}It shows which handler method matched, which is the quickest way to find out that the request went to a different mapping than you expected.
Sending a request body
For a POST set the content type and the body. Write the JSON as a text block for readability, or serialise an object with the ObjectMapper the application uses:
@Autowired
ObjectMapper json;
@Test
void createsAnOrderAndReturnsItsLocation() throws Exception {
when(orders.create(any())).thenReturn(new OrderResponse(8, "[email protected]", 3, "NEW"));
mvc.perform(post("/api/orders")
.contentType(MediaType.APPLICATION_JSON)
.content("""
{"customerEmail": "[email protected]", "quantity": 3}
"""))
.andExpect(status().isCreated())
.andExpect(header().string("Location", "/api/orders/8"))
.andExpect(jsonPath("$.id").value(8));
ArgumentCaptor<CreateOrderRequest> captured = ArgumentCaptor.forClass(CreateOrderRequest.class);
verify(orders).create(captured.capture());
assertThat(captured.getValue().quantity()).isEqualTo(3); // the body was bound correctly
}The captor verifies that Jackson turned the JSON into the right object, which tests the binding and the property names. This is the part a unit test of the method cannot do.
The failure paths
Controllers fail in interesting ways, and these are the tests that earn their keep. A request that violates validation:
@Test
void rejectsAnInvalidBodyWithAProblemResponse() throws Exception {
mvc.perform(post("/api/orders")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"customerEmail\": \"\", \"quantity\": 0}"))
.andExpect(status().isBadRequest());
verifyNoInteractions(orders); // validation stopped the request before the service
}Two assertions matter: the status, and that the service was never called. Add field specific error assertions if your handler produces them. A malformed JSON body gives a different exception, HttpMessageNotReadableException, also a 400; a wrong content type gives 415; an unsupported method gives 405. Write one test for each status the API promises, since those are the contract.
The exception handler is exercised the same way:
@Test
void unknownOrdersAreReportedAsProblemDetails() throws Exception {
when(orders.find(99L)).thenReturn(Optional.empty());
mvc.perform(get("/api/orders/99"))
.andExpect(status().isNotFound())
.andExpect(content().contentTypeCompatibleWith("application/problem+json"))
.andExpect(jsonPath("$.title").value("Order not found"));
}A path variable of the wrong type, /api/orders/abc, produces a 400 from MethodArgumentTypeMismatchException, and that too deserves a test if clients depend on it.
Security
With Spring Security on the classpath, @WebMvcTest includes the security filter chain, and requests are rejected without credentials. That is correct and it confuses people: tests that pass without security fail with 401 or 403 once it is added. Use the test support from spring-security-test to authenticate as a user and to supply the CSRF token for mutating requests:
@Test
@WithMockUser(roles = "USER")
void anAuthenticatedUserCanCreateAnOrder() throws Exception {
when(orders.create(any())).thenReturn(new OrderResponse(9, "[email protected]", 1, "NEW"));
mvc.perform(post("/api/orders")
.with(csrf())
.contentType(MediaType.APPLICATION_JSON)
.content("{\"customerEmail\": \"[email protected]\", \"quantity\": 1}"))
.andExpect(status().isCreated());
}
@Test
void anAnonymousUserIsRejected() throws Exception {
mvc.perform(get("/api/orders/7")).andExpect(status().isUnauthorized());
}
@Test
@WithMockUser(roles = "USER")
void aPostWithoutACsrfTokenIsForbidden() throws Exception {
mvc.perform(post("/api/orders").contentType(MediaType.APPLICATION_JSON).content("{}"))
.andExpect(status().isForbidden());
}@WithMockUser places a user in the security context without involving the real user store. The csrf() post processor adds a valid token; omitting it is how the third test proves CSRF protection is on. If your application uses a custom SecurityFilterChain, import it into the slice with @Import(SecurityConfig.class); without it, the slice applies Spring Boot's default security, and your rules are not under test. The authorisation rules themselves are tested more directly in testing permission checks.
File uploads and other request types
Multipart requests use the multipart builder:
@Test
void acceptsAnUploadedFile() throws Exception {
var file = new MockMultipartFile("file", "invoice.pdf", "application/pdf", "%PDF-1.7".getBytes());
mvc.perform(multipart("/api/orders/7/attachments").file(file).with(csrf()))
.andExpect(status().isCreated());
}The same family covers query parameters (.param("page", "2")), headers (.header("X-Request-Id", "abc")), cookies, session attributes and request attributes. Responses with a streamed body use asyncDispatch: perform the request, take request().asyncStarted() and then dispatch the result before asserting. For file downloads, assert on content().bytes(...) and header().string("Content-Disposition", ...).
@WebMvcTest or the full context
There are three ways to get a MockMvc, with different costs:
| Approach | Loads | Use for |
|---|---|---|
@WebMvcTest | Web slice only; services mocked | Most controller tests: fast and focused |
@SpringBootTest + @AutoConfigureMockMvc | Whole application | Wiring tests with real services and a database (Testcontainers) |
MockMvcBuilders.standaloneSetup(controller) | The controller you pass, with no Spring context | The very fastest, for a controller with trivial setup; you configure advice and converters by hand |
A balanced suite has many @WebMvcTest tests for each controller's contract and failure paths, and a small number of full tests that go from the HTTP request to the real database. Mocked services prove that the web layer is correct given the service's contract; they cannot prove the service honours it, which is the job of the integration tests described in unit versus integration tests and Spring Boot test slices.
Keeping it maintainable
Three habits keep a large MockMvc suite readable. Extract common request building into helpers, such as postJson(path, body). Keep JSON payloads in files under src/test/resources for large bodies and load them, or use text blocks for small ones. And assert the minimum that proves the behaviour; a test that checks every field of a large response breaks on every harmless change. For compatibility contracts that must not change, use a snapshot or schema approach, see Pact contract testing for Java.
Pitfalls
**Forgetting @MockitoBean.** A missing bean fails the slice at startup with NoSuchBeanDefinitionException for the controller's dependency. Mock every collaborator.
Testing with a real, empty context. Using standaloneSetup without the controller advice means your exception handler is not applied, and the test sees a raw 500. Register the advice explicitly with setControllerAdvice.
Asserting only on status. A 200 with the wrong body is a failure that status alone misses. Always assert on the body for success paths.
Time and randomness. Responses containing timestamps or generated ids need fixed clocks or matchers like jsonPath("$.id").exists().
When this does not apply
MockMvc runs inside the servlet mock environment, so it does not exercise the real servlet container: connector settings, TLS, HTTP/2, real filters in front of the application and Tomcat limits like multipart size are not tested. For those, use @SpringBootTest(webEnvironment = RANDOM_PORT) with RestClient or TestRestTemplate. For WebFlux controllers, use WebTestClient. The references are the Spring Framework testing documentation for MockMvc and the Spring Boot reference on testing Spring MVC.


