Sub topic 13
Testing error responses with MockMvc
An error contract is only a contract if something checks it. This chapter shows how to test the status code, content type and body of your error responses, without starting a server. It assumes you have the handlers from the earlier chapters: OrderNotFoundException, OrderController, CustomerController and the ApiExceptionHandler that extends ResponseEntityExceptionHandler. You should also know basic JUnit 5, and spring-boot-starter-test and spring-boot-starter-validation must be on the classpath.
What a @WebMvcTest slice gives you
@WebMvcTest starts only the web layer. It loads the controllers you name, @ControllerAdvice and @RestControllerAdvice beans, Jackson, validation and MockMvc. It does not load services, repositories or a real servlet container.
That makes it a good fit for error tests, because the advice bean is part of the slice. A request sent through MockMvc goes through the same DispatcherServlet, handler resolution and exception resolvers as a real request.
The basic pattern
Every error test has three steps:
- Perform a request that triggers the failure.
- Assert the HTTP status.
- Assert the parts of the body that clients depend on.
jsonPath takes a JSON path expression and compares the value it finds. Use it for fields such as title, status and your custom properties.
mockMvc.perform(get("/orders/99"))
.andExpect(status().isNotFound())
.andExpect(jsonPath("$.title").value("Order not found"))
.andExpect(jsonPath("$.orderId").value(99));Here orderId is a custom property set with problem.setProperty("orderId", ...). ProblemDetail serializes extra properties at the top level of the JSON object, so the path is $.orderId and not $.properties.orderId.
A fuller test class
The class below covers the cases that matter for this API:
- a missing order
- a validation failure
- a malformed JSON body
- a type mismatch in the path
- a
ResponseStatusException - an unexpected exception
It also has one test that checks internals do not leak.
The unexpected-exception test needs a controller that always fails. Put this class in your test sources, in the same package:
package com.example.orders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
class BrokenController {
@GetMapping("/broken")
String broken() {
throw new IllegalStateException("connection to db.internal:5432 failed, password=hunter2");
}
}Then the tests:
package com.example.orders;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
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.web.servlet.MockMvc;
@WebMvcTest(controllers = {OrderController.class, CustomerController.class, BrokenController.class})
class OrderControllerErrorTest {
@Autowired
MockMvc mockMvc;
@Test
void unknownOrderReturnsProblemDetail() throws Exception {
mockMvc.perform(get("/orders/99"))
.andExpect(status().isNotFound())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.title").value("Order not found"))
.andExpect(jsonPath("$.detail").value("Order 99 was not found"))
.andExpect(jsonPath("$.orderId").value(99));
}
@Test
void blankItemReturnsFieldErrors() throws Exception {
mockMvc.perform(post("/orders")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"item\":\"\",\"quantity\":1}"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.title").value("Invalid request"))
.andExpect(jsonPath("$.errors[0]").value("item: must not be blank"));
}
@Test
void malformedJsonReturnsBadRequest() throws Exception {
mockMvc.perform(post("/orders")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"item\":"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.status").value(400));
}
@Test
void nonNumericIdReturnsBadRequest() throws Exception {
mockMvc.perform(get("/orders/abc"))
.andExpect(status().isBadRequest());
}
@Test
void responseStatusExceptionKeepsItsStatusAndReason() throws Exception {
mockMvc.perform(get("/customers/5"))
.andExpect(status().isNotFound())
.andExpect(jsonPath("$.detail").value("Customer 5 was not found"));
}
@Test
void unexpectedExceptionDoesNotLeakInternals() throws Exception {
mockMvc.perform(get("/broken"))
.andExpect(status().isInternalServerError())
.andExpect(jsonPath("$.title").value("Internal server error"))
.andExpect(jsonPath("$.detail").value("An unexpected error occurred"))
.andExpect(content().string(not(containsString("hunter2"))))
.andExpect(content().string(not(containsString("db.internal"))));
}
}Reading the assertions
- Content type.
ProblemDetailbodies are sent asapplication/problem+json.contentTypeCompatibleWithaccepts that type and ignores parameters such as the charset. Asserting it once protects clients that dispatch on the media type. - Standard fields.
type,title,status,detailandinstancecome from RFC 9457. When you do not settype, it defaults toabout:blank. Assert only the fields you promise to clients. - Field order in lists.
$.errors[0]is safe in the validation test because only one field is invalid. If a request can fail on several fields, the order of the errors is not guaranteed. Assert the whole list withjsonPath("$.errors", containsInAnyOrder(...))or check each entry with a filter expression such as$.errors[?(@ =~ /item.*/)]. - Negative checks. The leak test is the only one that asserts something is absent. Put a recognizable fake secret in the exception message, as
BrokenControllerdoes, and check that it never appears in the body. A test like this fails the day someone changes the catch-all handler to returnex.getMessage().
Testing the cases the framework handles for you
ApiExceptionHandler extends ResponseEntityExceptionHandler, so you get handling for many standard MVC exceptions without writing code. These include:
- unreadable JSON
- type mismatches
- unsupported media types
- missing parameters
You still test them. The tests do not check Spring's code. They check that your handler chain turns each of them into the response shape you promise. Extending the base class is what keeps these cases from falling into your Exception.class handler and becoming 500s.
If you remove the base class, malformedJsonReturnsBadRequest fails. The Exception handler catches the HttpMessageNotReadableException and returns 500. That is the kind of regression these tests exist to catch.
Properties in slice tests
@WebMvcTest reads application.properties from your main resources. A property such as spring.mvc.problemdetails.enabled=true therefore applies in the slice. It only affects Spring MVC's own exceptions when no advice already handles them. Because ApiExceptionHandler extends ResponseEntityExceptionHandler, your advice produces those responses in both cases.
If a test depends on a property, you can set it explicitly so the dependency is visible:
@WebMvcTest(controllers = OrderController.class, properties = "spring.mvc.problemdetails.enabled=true")
class OrderControllerProblemDetailsTest {
// tests here
}Debugging failing assertions
When an assertion fails, you need to see the real response. Add andDo(print()) before the expectations:
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
mockMvc.perform(get("/orders/99"))
.andDo(print())
.andExpect(status().isNotFound());print() writes the request, the handler that ran, any resolved exception, and the full response body to the console. Check the "Resolved Exception" section first. It tells you whether your advice ran or the default resolver did.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `NoSuchBeanDefinitionException` for a service | The controller depends on a bean the slice does not load | Add `@MockitoBean` (Spring Framework 6.2 and later) or `@MockBean` for it |
| 500 where you expected 404 | Advice not loaded, or the `Exception` handler caught the exception first | Check the "Resolved Exception" in `print()`, and check the advice is in a scanned package |
| `ServletException` thrown from `perform` | No handler resolved the exception | Add a handler, or test the default `/error` path with `@SpringBootTest` |
| Validation test returns 201 | `spring-boot-starter-validation` missing, or `@Valid` missing on the parameter | Add the dependency and the annotation |
| `jsonPath` finds no value | Wrong path, for example `$.properties.orderId` | Print the body and match the real structure |
| `orderId` comparison fails | Comparing against a type that differs from the parsed JSON number | Use `.value(99)` for small numbers. JSON numbers parse as `Integer` before `Long` |
What to cover, and what to skip
A useful error test suite is small and aimed at the contract:
- One test per handler method in the advice.
- One validation test per request type, covering at least one failing field.
- One test for each framework exception you rely on the base class to handle.
- One leak test for the catch-all handler.
Skip testing the exact wording of Spring's built-in messages, such as the text of a type mismatch. Those strings can change between releases. Assert status, title, type and your own properties, which you control.
Exercise
A teammate adds a handler for IllegalArgumentException that returns 400 with the exception message as detail. Write the single assertion you would add to the "unexpected exception" test style to prove the new handler does not expose a database hostname placed in the exception message. Which MockMvc call checks the raw response body?
Show answer
Throw an IllegalArgumentException containing the hostname from a test controller, perform the request, and assert content().string(not(containsString("db.internal"))). content().string(...) checks the raw body text, so it also catches the hostname if it appears in any field, not only in detail. A better outcome is that the test fails and the handler is changed to return a fixed message and log the real one.
Exercise
Why does a @WebMvcTest test for a request that no handler resolves fail with an exception instead of a 500 status?
Show answer
MockMvc does not perform the servlet container's error-page forward to /error. An unresolved exception propagates out of perform as a ServletException. To see the default 500 response from BasicErrorController, run a @SpringBootTest with a real or random port.