Validation and error responses in controller tests
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite's category API works for good requests. Real clients also send empty names, unknown fields and missing categories. How do you prove the API answers each of those correctly, every time?
POST with a JSON body and content type
A content type is the Content-Type header that tells the server what format the request body is in, such as application/json. Spring uses it to pick the converter that reads the body.
Build a request with a JSON body and a content type. Without the content type, ShopLite answers 415, as its contract says.
mockMvc.perform(post("/api/v1/categories") .contentType(MediaType.APPLICATION_JSON) .content(""" {"name": "Wearables", "parentId": 1} """)) .andExpect(status().isCreated());Java text blocks (""") keep the JSON readable inside the test. Write the body as a client would send it, not by serialising a Java object: the test then also proves the field names.
Example 1 runs a tiny com.sun.net.httpserver handler and a real HttpClient, so you can watch both cases over HTTP with plain Java.
Example 1 · POST with and without a JSON content type, over real HTTP
import com.sun.net.httpserver.HttpExchange;import com.sun.net.httpserver.HttpServer;
import java.io.IOException;import java.io.OutputStream;import java.net.InetSocketAddress;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.nio.charset.StandardCharsets;
/** A tiny POST /api/v1/categories handler: 415 without JSON, 201 + Location with it. */class CategoryHandler { private int nextId = 8;
void handle(HttpExchange exchange) throws IOException { String type = exchange.getRequestHeaders().getFirst("Content-Type"); if (type == null || !type.startsWith("application/json")) { send(exchange, 415, "application/problem+json", "{\"title\":\"Unsupported media type\",\"status\":415}"); return; } String body = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8); String name = body.replaceAll(".*\"name\"\\s*:\\s*\"([^\"]*)\".*", "$1"); // enough for this demo int id = nextId++; String host = exchange.getRequestHeaders().getFirst("Host"); exchange.getResponseHeaders().add("Location", "http://" + host + "/api/v1/categories/" + id); send(exchange, 201, "application/json", "{\"id\":" + id + ",\"name\":\"" + name + "\",\"parentId\":null}"); }
private static void send(HttpExchange exchange, int status, String type, String json) throws IOException { byte[] bytes = json.getBytes(StandardCharsets.UTF_8); exchange.getResponseHeaders().add("Content-Type", type); exchange.sendResponseHeaders(status, bytes.length); try (OutputStream out = exchange.getResponseBody()) { out.write(bytes); } }}
public class CategoryPostDemo { public static void main(String[] args) throws Exception { HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0); // port 0: any free port CategoryHandler handler = new CategoryHandler(); server.createContext("/api/v1/categories", handler::handle); server.start(); String base = "http://localhost:" + server.getAddress().getPort(); HttpClient client = HttpClient.newHttpClient(); try { HttpRequest noType = HttpRequest.newBuilder(URI.create(base + "/api/v1/categories")) .POST(HttpRequest.BodyPublishers.ofString("{\"name\": \"Wearables\"}")) .build(); HttpResponse<String> r1 = client.send(noType, HttpResponse.BodyHandlers.ofString()); System.out.println("No Content-Type -> " + r1.statusCode() + " " + r1.body());
HttpRequest json = HttpRequest.newBuilder(URI.create(base + "/api/v1/categories")) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString("{\"name\": \"Wearables\"}")) .build(); HttpResponse<String> r2 = client.send(json, HttpResponse.BodyHandlers.ofString()); String location = r2.headers().firstValue("Location").orElse("none"); System.out.println("application/json -> " + r2.statusCode() + " " + r2.body()); System.out.println("Location ends with /api/v1/categories/8: " + location.endsWith("/api/v1/categories/8")); System.out.println("Location is absolute: " + location.startsWith("http://localhost:")); } finally { server.stop(0); } }}No Content-Type -> 415 {"title":"Unsupported media type","status":415}
application/json -> 201 {"id":8,"name":"Wearables","parentId":null}
Location ends with /api/v1/categories/8: true
Location is absolute: trueWhat this code does
HttpServer.create(new InetSocketAddress("localhost", 0), 0)takes any free port, likeRANDOM_PORTin a Spring test. The program prints no port, so the output is the same on every run.- Without
Content-Type: application/jsonthe handler answers 415, the status ShopLite gives for a body that is not JSON. - With JSON it answers 201 and an absolute
Locationbuilt from the request'sHostheader, the same idea asServletUriComponentsBuilder.fromCurrentRequest().
400 ProblemDetail for invalid fields and unknown properties
ProblemDetail is the standard JSON error body (RFC 9457) with the fields type, title, status, detail and instance. ShopLite sends one for every error, so a test can check the exact answer a client will see.
Send broken bodies and check the 400 answers. Example 2 runs four bad requests through the real validation; Example 3 is a hand-written checker in plain Java.
Example 2 · src/test/java/com/shoplite/category/CategoryValidationTest.java
Runs in: the shoplite-api Spring Boot project
package com.shoplite.category;
import static org.mockito.Mockito.verifyNoInteractions;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.webmvc.test.autoconfigure.WebMvcTest;import org.springframework.context.annotation.Import;import org.springframework.http.MediaType;import org.springframework.test.context.bean.override.mockito.MockitoBean;import org.springframework.test.web.servlet.MockMvc;
import com.shoplite.common.OpenWebMvcTestSecurity;
/** Bad category bodies: each one is a 400 ProblemDetail, and the service is never called. */@WebMvcTest(CategoryController.class)@Import(OpenWebMvcTestSecurity.class)class CategoryValidationTest {
@Autowired private MockMvc mockMvc;
@MockitoBean private CategoryService categoryService;
@Test void tooShortNameIsValidationFailed() throws Exception { mockMvc.perform(post("/api/v1/categories") .contentType(MediaType.APPLICATION_JSON) .content(""" {"name": "K", "parentId": 1} """)) .andExpect(status().isBadRequest()) .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) .andExpect(jsonPath("$.type").value("https://shoplite.example/problems/validation-failed")) .andExpect(jsonPath("$.detail").value("The request has 1 invalid field.")) .andExpect(jsonPath("$.errors[0].field").value("name")) .andExpect(jsonPath("$.errors[0].message").value("must be 2-50 characters")); verifyNoInteractions(categoryService); }
@Test void missingNameIsValidationFailed() throws Exception { mockMvc.perform(post("/api/v1/categories") .contentType(MediaType.APPLICATION_JSON) .content(""" {"parentId": 1} """)) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.errors[0].message").value("must not be blank")); verifyNoInteractions(categoryService); }
@Test void unknownFieldIsMalformedRequest() throws Exception { mockMvc.perform(post("/api/v1/categories") .contentType(MediaType.APPLICATION_JSON) .content(""" {"id": 8, "name": "Wearables"} """)) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.title").value("Malformed request")) .andExpect(jsonPath("$.detail").value("Unknown field id.")); verifyNoInteractions(categoryService); }
@Test void plainTextBodyIs415() throws Exception { mockMvc.perform(post("/api/v1/categories") .contentType(MediaType.TEXT_PLAIN) .content("Wearables")) .andExpect(status().isUnsupportedMediaType()) .andExpect(jsonPath("$.title").value("Unsupported media type")); verifyNoInteractions(categoryService); }}[INFO] Running com.shoplite.category.CategoryValidationTest
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 3.744 s -- in com.shoplite.category.CategoryValidationTest
The response of the first test (print it with .andDo(print()); headers left out):
MockHttpServletResponse:
Status = 400
Error message = null
Content type = application/problem+json
Body = {"type":"https://shoplite.example/problems/validation-failed","title":"Validation failed","status":400,"detail":"The request has 1 invalid field.","instance":"/api/v1/categories","errors":[{"field":"name","message":"must be 2-50 characters"}]}What this code does
- Four bad bodies, four 400/415 answers, and
verifyNoInteractionseach time: validation and parsing stop the request before the controller method. - "K" breaks only
@Size("must be 2-50 characters"); a missing name breaks only@NotBlank, because@Sizelets null through. - The printed response shows the full ProblemDetail: the contract's field order,
instancefilled in, and theerrorsextension.
Example 3 · A hand-written validator: every broken field, in body order
import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.Set;
record InvalidField(String field, String message) {}
/** Checks a category body the way ShopLite's rules say, and builds the problem JSON. */class CategoryBodyChecker { private static final Set<String> KNOWN = Set.of("name", "parentId");
static String check(Map<String, Object> body) { for (String key : body.keySet()) { if (!KNOWN.contains(key)) { return problem("malformed-request", "Malformed request", "Unknown field " + key + ".", List.of()); } } List<InvalidField> errors = new ArrayList<>(); Object raw = body.get("name"); String name = raw == null ? null : raw.toString().strip(); if (name == null || name.isEmpty()) { errors.add(new InvalidField("name", "must not be blank")); } else if (name.length() < 2 || name.length() > 50) { errors.add(new InvalidField("name", "must be 2-50 characters")); } if (errors.isEmpty()) { return "valid"; } String detail = "The request has " + errors.size() + (errors.size() == 1 ? " invalid field." : " invalid fields."); return problem("validation-failed", "Validation failed", detail, errors); }
private static String problem(String kind, String title, String detail, List<InvalidField> errors) { StringBuilder json = new StringBuilder("{\"type\":\"https://shoplite.example/problems/" + kind + "\",\"title\":\"" + title + "\",\"status\":400,\"detail\":\"" + detail + "\""); if (!errors.isEmpty()) { json.append(",\"errors\":["); for (int i = 0; i < errors.size(); i++) { InvalidField e = errors.get(i); json.append(i == 0 ? "" : ",").append("{\"field\":\"").append(e.field()) .append("\",\"message\":\"").append(e.message()).append("\"}"); } json.append("]"); } return json.append("}").toString(); }}
public class ValidationProblemDemo { static Map<String, Object> body(Object... pairs) { Map<String, Object> map = new LinkedHashMap<>(); for (int i = 0; i < pairs.length; i += 2) { map.put((String) pairs[i], pairs[i + 1]); } return map; }
public static void main(String[] args) { System.out.println(CategoryBodyChecker.check(body("name", "Wearables", "parentId", 1))); System.out.println(CategoryBodyChecker.check(body("name", "K"))); System.out.println(CategoryBodyChecker.check(body("parentId", 1))); System.out.println(CategoryBodyChecker.check(body("id", 8, "name", "Wearables"))); }}valid
{"type":"https://shoplite.example/problems/validation-failed","title":"Validation failed","status":400,"detail":"The request has 1 invalid field.","errors":[{"field":"name","message":"must be 2-50 characters"}]}
{"type":"https://shoplite.example/problems/validation-failed","title":"Validation failed","status":400,"detail":"The request has 1 invalid field.","errors":[{"field":"name","message":"must not be blank"}]}
{"type":"https://shoplite.example/problems/malformed-request","title":"Malformed request","status":400,"detail":"Unknown field id."}What this code does
- The checker builds the same JSON shape as ShopLite:
type,title,status,detail, thenerrors. - An unknown key is rejected before any field rule, like Jackson failing to read the body before Bean Validation runs.
detailcounts fields, not messages: "The request has 1 invalid field."
Bean Validation checks the @NotBlank and @Size rules on CategoryRequest before the controller method runs. A broken field gives 400 validation-failed with an errors list of {field, message}. An unknown field such as id gives 400 malformed-request, because ShopLite sets fail-on-unknown-properties=true.
The slice runs the real validation and the real GlobalExceptionHandler. verifyNoInteractions(categoryService) proves a bad request never reached the service. The fields come out in the contract's order because ShopLite turns off Jackson 3's alphabetical sorting in application.properties.
Predict the output
Which error comes back?
Read each request and pick the answer ShopLite sends.
Round 1 of 3
Which answer comes back?
.andDo(print()) (from MockMvcResultHandlers) to see the full request and response in the test log while you write a test. Remove it afterwards.404 from ResourceNotFoundException through the global handler
A global exception handler is one class marked @RestControllerAdvice that turns exceptions thrown anywhere in the controllers into error responses. ShopLite maps each of its exceptions to one status and ProblemDetail.
Make the mock service throw a ShopLite exception and check the response the handler builds. Example 4 tests 404, 409 and 422 this way.
Example 4 · src/test/java/com/shoplite/category/CategoryErrorResponsesTest.java
Runs in: the shoplite-api Spring Boot project
package com.shoplite.category;
import static org.mockito.ArgumentMatchers.any;import static org.mockito.ArgumentMatchers.eq;import static org.mockito.BDDMockito.given;import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;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.webmvc.test.autoconfigure.WebMvcTest;import org.springframework.context.annotation.Import;import org.springframework.http.MediaType;import org.springframework.test.context.bean.override.mockito.MockitoBean;import org.springframework.test.web.servlet.MockMvc;
import com.shoplite.common.AlreadyExistsException;import com.shoplite.common.BusinessRuleException;import com.shoplite.common.OpenWebMvcTestSecurity;import com.shoplite.common.ResourceNotFoundException;
/** Service exceptions become the contract's 404, 409 and 422 problems in GlobalExceptionHandler. */@WebMvcTest(CategoryController.class)@Import(OpenWebMvcTestSecurity.class)class CategoryErrorResponsesTest {
private static final String WEARABLES = """ {"name": "Wearables", "parentId": 1} """;
@Autowired private MockMvc mockMvc;
@MockitoBean private CategoryService categoryService;
@Test void replacingAMissingCategoryIs404() throws Exception { given(categoryService.replace(eq(99), any())).willThrow(new ResourceNotFoundException("Category", 99));
mockMvc.perform(put("/api/v1/categories/99").contentType(MediaType.APPLICATION_JSON).content(WEARABLES)) .andExpect(status().isNotFound()) .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) .andExpect(jsonPath("$.type").value("https://shoplite.example/problems/not-found")) .andExpect(jsonPath("$.title").value("Resource not found")) .andExpect(jsonPath("$.status").value(404)) .andExpect(jsonPath("$.detail").value("Category 99 was not found.")) .andExpect(jsonPath("$.instance").value("/api/v1/categories/99")); }
@Test void duplicateNameIs409AlreadyExists() throws Exception { given(categoryService.create(any())) .willThrow(new AlreadyExistsException("A category named Mobiles already exists."));
mockMvc.perform(post("/api/v1/categories").contentType(MediaType.APPLICATION_JSON) .content(""" {"name": "Mobiles", "parentId": 1} """)) .andExpect(status().isConflict()) .andExpect(jsonPath("$.type").value("https://shoplite.example/problems/already-exists")) .andExpect(jsonPath("$.detail").value("A category named Mobiles already exists.")); }
@Test void unknownParentIs422RuleBroken() throws Exception { given(categoryService.create(any())) .willThrow(new BusinessRuleException("Parent category 42 does not exist."));
mockMvc.perform(post("/api/v1/categories").contentType(MediaType.APPLICATION_JSON) .content(""" {"name": "Wearables", "parentId": 42} """)) .andExpect(status().isUnprocessableContent()) .andExpect(jsonPath("$.title").value("Business rule broken")) .andExpect(jsonPath("$.detail").value("Parent category 42 does not exist.")); }}[INFO] Running com.shoplite.category.CategoryErrorResponsesTest [INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.288 s -- in com.shoplite.category.CategoryErrorResponsesTest
What this code does
willThrow(...)makes the mock fail the way the real service would; the test then checks the problem kind, status and text.- The 404 test checks all five fields once; the others check the fields that differ (
type,title,detail). isUnprocessableContent()is 422, the name used by RFC 9110 and Spring 7 (older code saysisUnprocessableEntity()).
GlobalExceptionHandler turns ResourceNotFoundException into 404 not-found, AlreadyExistsException into 409 already-exists and BusinessRuleException into 422 rule-broken. Check all five ProblemDetail fields once per kind, and the application/problem+json content type. instance is the request path: Spring fills it in when the handler leaves it empty.
This is the controller's half of the contract. The service's half, that replace(99, ...) really throws ResourceNotFoundException, belongs in the service unit test.
Order of execution
Follow a 404
Put the steps of the 404 test in the order they happen.
Checking Location headers and 201 Created
Location is the response header that holds the absolute URL of the item a POST just created. ShopLite sends it with 201 Created, so the client knows where to read the new item.
Create a category and check three things: the 201 status, the Location header and the id in the body. Then delete one and check 204 with no body.
Example 5 · src/test/java/com/shoplite/category/CategoryCreateDeleteTest.java
Runs in: the shoplite-api Spring Boot project
package com.shoplite.category;
import static org.mockito.ArgumentMatchers.any;import static org.mockito.BDDMockito.given;import static org.mockito.BDDMockito.then;import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;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.header;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.webmvc.test.autoconfigure.WebMvcTest;import org.springframework.context.annotation.Import;import org.springframework.http.MediaType;import org.springframework.test.context.bean.override.mockito.MockitoBean;import org.springframework.test.web.servlet.MockMvc;
import com.shoplite.common.OpenWebMvcTestSecurity;
@WebMvcTest(CategoryController.class)@Import(OpenWebMvcTestSecurity.class)class CategoryCreateDeleteTest {
@Autowired private MockMvc mockMvc;
@MockitoBean private CategoryService categoryService;
@Test void createReturns201WithLocationAndTheCategory() throws Exception { given(categoryService.create(any())).willReturn(new CategoryResponse(8, "Wearables", 1));
mockMvc.perform(post("/api/v1/categories") .contentType(MediaType.APPLICATION_JSON) .content(""" {"name": " Wearables ", "parentId": 1} """)) .andExpect(status().isCreated()) .andExpect(header().string("Location", "http://localhost/api/v1/categories/8")) .andExpect(jsonPath("$.id").value(8)) .andExpect(jsonPath("$.name").value("Wearables"));
// The record's constructor trimmed the name before the service saw it then(categoryService).should().create(new CategoryRequest("Wearables", 1)); }
@Test void deleteReturns204WithNoBody() throws Exception { mockMvc.perform(delete("/api/v1/categories/8")) .andExpect(status().isNoContent()) .andExpect(content().string("")); then(categoryService).should().delete(8); }}[INFO] Running com.shoplite.category.CategoryCreateDeleteTest [INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.214 s -- in com.shoplite.category.CategoryCreateDeleteTest
What this code does
Locationishttp://localhost/api/v1/categories/8: MockMvc's request host with no port, plus the new id from the mocked service.then(categoryService).should().create(new CategoryRequest("Wearables", 1))passes because records compare by value and the compact constructor stripped the spaces.- The delete test checks both 204 and an empty body: a 204 must never carry JSON.
header().string("Location", ...) checks the header. ShopLite builds it from the current request, so in MockMvc it is http://localhost/api/v1/categories/8: the mock request's host is localhost on port 80, which URLs leave out. For a delete, check status().isNoContent() and an empty body.
then(categoryService).should().create(...) (BDDMockito's verify) shows what reached the service. Here it proves the record trimmed " Wearables " to "Wearables" before the service saw it.
Fix the error
Fix the Location check
The create test fails on the header. Pick the correct line 4.
Which replacement for line 4 makes the test pass?
Error
Response header 'Location' expected:<http://localhost:8080/api/v1/categories/8> but was:<http://localhost/api/v1/categories/8>
Next step
Check your understanding
11 quick questions