Sub topic 13
Testing error responses with MockMvc
This chapter assumes you have built the OrderController, OrderNotFoundException and ApiExceptionHandler from the earlier chapters. You should also know basic JUnit 5. The goal is to prove that each failure produces the status code and ProblemDetail body you designed.
Why test errors separately
Error handling is easy to break without noticing. Renaming a field, removing an @ExceptionHandler or changing a validation annotation can silently turn a clean 404 into a 500. A test fixes the error contract in place, so clients can rely on it.
Choosing the slice
@WebMvcTest starts only the web layer. It registers the named controller, @RestControllerAdvice classes, Jackson and validation. It does not start a server or load services and repositories. Because ApiExceptionHandler is loaded, the test runs the same handler chain as production.
MockMvc sends a request straight into Spring's DispatcherServlet. This makes the tests fast and deterministic.
Dependencies
You need spring-boot-starter-test for MockMvc and JUnit. You also need spring-boot-starter-validation so that @Valid is enforced. Without the validation starter, the blank-item test below would return 201 instead of 400.
The tests
package com.example.orders;
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.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(OrderController.class)
class OrderControllerErrorTest {
@Autowired
MockMvc mockMvc;
@Test
void unknownOrderReturnsProblemDetail() throws Exception {
mockMvc.perform(get("/orders/99"))
.andExpect(status().isNotFound())
.andExpect(jsonPath("$.title").value("Order 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("$.errors[0]").value("item: must not be blank"));
}
}Reading the assertions
status().isNotFound()checks the HTTP code. This is the first thing clients depend on.jsonPath("$.title")reads a field from the JSON body.ProblemDetailserializestitle,statusanddetailat the top level.jsonPath("$.orderId")reads the extra property set withsetProperty. Extra properties also appear at the top level, not under a nested key.$.errors[0]reads the first entry of the list built fromgetFieldErrors().
Common mistakes
- Testing the message text too strictly.
must not be blankcomes from the validation library and depends on the locale. If the wording matters little, assert on the field name withcontainsString. - Forgetting the content type. A
POSTwithoutcontentType(MediaType.APPLICATION_JSON)gives a 415 response, not a validation error. - Missing advice in the slice. If you use a narrower test setup that omits the advice class, the default
/errorhandling applies and yourProblemDetailassertions fail.
Where to go next
For each new exception handler, write one test that triggers it. Cover the catch-all 500 handler too. It needs a controller method or a mocked @MockitoBean service that throws a plain RuntimeException.
Exercise
A test posts {"item":"Pen","quantity":0} to /orders and expects a 400, but the response is 201. The request body and content type are correct. What is the most likely cause?
Show answer
The spring-boot-starter-validation dependency is missing, so @Valid and @Positive are not enforced. Add the starter. Then quantity: must be greater than 0 is reported in the errors list with a 400 status.