Sub topic 14
Testing validation
Validation rules are code, and they break like code. A constraint can be removed by accident. @Valid can be dropped from a controller parameter. An exception handler can start returning 500 instead of 400. This chapter shows how to test each layer with the cheapest test that catches the problem.
This chapter assumes you know JUnit 5 and AssertJ basics, and that you have the DTO, controller, ApiExceptionHandler and AllowedCountry constraint from the earlier chapters. It also assumes you know what @WebMvcTest is.
Choosing the test level
Validation behavior lives in three places, and each place has its own test.
| What you want to verify | Test type | Spring context needed |
|---|---|---|
| Constraints on a DTO are correct | Plain `Validator` test | No |
| A custom `ConstraintValidator` works | Plain `Validator` or direct unit test | No |
| `@Valid` is present and the 400 response has the right shape | `@WebMvcTest` with `MockMvc` | Web slice only |
| Constraints on path variables or parameters work | `@WebMvcTest` with `MockMvc` | Web slice only |
Plain Validator tests start in milliseconds and pinpoint a wrong constraint. MockMvc tests take longer, but they are the only tests that notice a missing @Valid or a broken handler. Write both.
Test dependencies
spring-boot-starter-test brings JUnit 5, AssertJ, Mockito and MockMvc support. The validation starter already supplies Hibernate Validator and the expression language implementation it needs to build messages.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>Testing constraints with a plain Validator
The Validator can be built without Spring. The test creates a ValidatorFactory once, validates objects, and inspects the returned set of ConstraintViolation objects. An empty set means the object is valid.
import static org.assertj.core.api.Assertions.assertThat;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import java.util.Set;
import java.util.stream.Collectors;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
class CreateUserRequestTest {
private static ValidatorFactory factory;
private static Validator validator;
@BeforeAll
static void setUp() {
factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
}
@AfterAll
static void tearDown() {
factory.close();
}
private Set<String> invalidFields(CreateUserRequest request) {
return validator.validate(request).stream()
.map(violation -> violation.getPropertyPath().toString())
.collect(Collectors.toSet());
}
@Test
void acceptsValidRequest() {
var request = new CreateUserRequest("Ada", "[email protected]", 36);
assertThat(validator.validate(request)).isEmpty();
}
@Test
void rejectsBlankName() {
var request = new CreateUserRequest(" ", "[email protected]", 36);
assertThat(invalidFields(request)).containsExactly("name");
}
@Test
void rejectsMalformedEmail() {
var request = new CreateUserRequest("Ada", "not-an-email", 36);
assertThat(invalidFields(request)).containsExactly("email");
}
@Test
void rejectsUnderageUser() {
var request = new CreateUserRequest("Ada", "[email protected]", 17);
assertThat(invalidFields(request)).containsExactly("age");
}
@Test
void reportsNullAgeOnlyOnce() {
var request = new CreateUserRequest("Ada", "[email protected]", null);
assertThat(invalidFields(request)).containsExactly("age");
}
}The last test shows a rule that is easy to forget. @Min treats null as valid, so a missing age fails only @NotNull. If you remove @NotNull later, this test fails and tells you that null now gets through.
Assert on the property path and constraint type, not the message
Messages are text. They change when you edit wording, when you move them into ValidationMessages.properties, or when the JVM default locale differs from yours. Two sturdier options exist:
- Assert on
getPropertyPath(), as above. - Assert on the annotation type through
violation.getConstraintDescriptor().getAnnotation().annotationType().
@Test
void underageFailsTheMinConstraint() {
var request = new CreateUserRequest("Ada", "[email protected]", 17);
var violation = validator.validate(request).iterator().next();
assertThat(violation.getConstraintDescriptor().getAnnotation().annotationType())
.isEqualTo(jakarta.validation.constraints.Min.class);
}If you must assert on message text, pin the locale with Locale.setDefault(Locale.ENGLISH) in @BeforeAll. Restore it in @AfterAll, because the default locale is global JVM state.
Testing a custom constraint
A custom constraint has two parts, the annotation and its validator. Test the validator logic directly, then test the annotation wiring through a real Validator. The wiring test catches a wrong validatedBy or a missing @Retention(RUNTIME).
import static org.assertj.core.api.Assertions.assertThat;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
class AllowedCountryTest {
record Shipping(@AllowedCountry String country) {
}
private static ValidatorFactory factory;
private static Validator validator;
@BeforeAll
static void setUp() {
factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
}
@AfterAll
static void tearDown() {
factory.close();
}
@Test
void validatorLogicAcceptsSupportedAndNull() {
var logic = new AllowedCountryValidator();
assertThat(logic.isValid("DE", null)).isTrue();
assertThat(logic.isValid(null, null)).isTrue();
assertThat(logic.isValid("XX", null)).isFalse();
}
@Test
void annotationIsWiredToTheValidator() {
var violations = validator.validate(new Shipping("XX"));
assertThat(violations).hasSize(1);
assertThat(violations.iterator().next().getMessage())
.isEqualTo("country is not supported");
}
@Test
void supportedCountryPasses() {
assertThat(validator.validate(new Shipping("FR"))).isEmpty();
}
}This test class must be in the same package as AllowedCountryValidator, because that class is package-private. The null assertion documents the convention that @NotNull is a separate rule.
If a validator needs injected beans, such as a repository for a uniqueness check, a bare Validator cannot construct it. Either unit-test the validator class with a mock, or use a Spring-managed Validator in a @SpringBootTest.
Testing the HTTP contract with MockMvc
@WebMvcTest loads the controller, its @RestControllerAdvice beans, Jackson and the validation auto-configuration. It does not load services or repositories. This is the right place to verify that @Valid is present and that failures become a structured 400.
import static org.hamcrest.Matchers.aMapWithSize;
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(UserController.class)
class UserControllerTest {
@Autowired
MockMvc mockMvc;
@Test
void createsUserWhenBodyIsValid() throws Exception {
mockMvc.perform(post("/users")
.contentType(MediaType.APPLICATION_JSON)
.content("""
{"name":"Ada","email":"[email protected]","age":36}
"""))
.andExpect(status().isCreated());
}
@Test
void returnsOneErrorPerInvalidField() throws Exception {
mockMvc.perform(post("/users")
.contentType(MediaType.APPLICATION_JSON)
.content("""
{"name":"","email":"nope","age":10}
"""))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.detail").value("Validation failed"))
.andExpect(jsonPath("$.errors", aMapWithSize(3)))
.andExpect(jsonPath("$.errors.age")
.value("must be greater than or equal to 18"));
}
@Test
void rejectsMissingAge() throws Exception {
mockMvc.perform(post("/users")
.contentType(MediaType.APPLICATION_JSON)
.content("""
{"name":"Ada","email":"[email protected]"}
"""))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.errors.age").value("must not be null"));
}
}The second test fails if someone removes @Valid from the controller, because the request would then return 201. A plain Validator test cannot catch that mistake. The advice class is discovered automatically, so the $.errors structure from the previous chapters is exercised too.
Testing path variable validation
Class-level @Validated works through a proxy and throws ConstraintViolationException. That exception is not a MethodArgumentNotValidException, so your existing handler does not catch it. Add a handler, then test it.
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class ConstraintViolationAdvice {
@ExceptionHandler(ConstraintViolationException.class)
public ProblemDetail handle(ConstraintViolationException ex) {
ProblemDetail problem =
ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Validation failed");
Map<String, String> errors = new LinkedHashMap<>();
for (ConstraintViolation<?> violation : ex.getConstraintViolations()) {
errors.putIfAbsent(violation.getPropertyPath().toString(), violation.getMessage());
}
problem.setProperty("errors", errors);
return problem;
}
}import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
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.test.web.servlet.MockMvc;
@WebMvcTest(OrderController.class)
class OrderControllerTest {
@Autowired
MockMvc mockMvc;
@Test
void acceptsPositiveId() throws Exception {
mockMvc.perform(get("/orders/5"))
.andExpect(status().isOk())
.andExpect(content().string("order 5"));
}
@Test
void rejectsZeroId() throws Exception {
mockMvc.perform(get("/orders/0"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.errors").isNotEmpty());
}
}The property path for a parameter violation looks like find.id. The parameter name appears only when the code is compiled with the -parameters flag, which the Spring Boot Maven and Gradle plugins enable. Otherwise you see find.arg0. This is why the test checks that $.errors is not empty instead of naming the key.
Testing groups
If you use validation groups, pass the group as an extra argument. Test both directions, so that a rule applies when its group is requested and does not apply otherwise.
var onCreate = validator.validate(request, OnCreate.class);
var onUpdate = validator.validate(request, OnUpdate.class);Default is a group too. A constraint with no groups attribute belongs to Default, and validating with only OnCreate skips it. A test that requests the wrong group passes for the wrong reason.
Common mistakes
- Missing content type. Without
contentType(MediaType.APPLICATION_JSON),MockMvcreturns 415 before validation runs. - Malformed JSON mistaken for invalid data. A body that does not parse produces
HttpMessageNotReadableException, not a validation error. Unparseable input is a separate test case. - Asserting on the full message string everywhere. One reworded message then breaks many tests. Assert on field names, and keep message text checks to a few tests.
- Expecting service-layer validation in a web slice.
@WebMvcTestdoes not create service beans. Use@SpringBootTest, or a plainValidatortest, for rules that belong to the service. - Reusing a
Validatorafter closing its factory. Create the factory once per class and close it in@AfterAll.
Exercise
A teammate removes @Valid from the @RequestBody parameter of UserController.create. Which of the tests in this chapter fail, and which keep passing?
Show answer
The MockMvc test returnsOneErrorPerInvalidField fails, because the invalid body now returns 201 instead of 400. rejectsMissingAge fails for the same reason. The plain Validator tests in CreateUserRequestTest keep passing, because they never go through the controller. This is why you need both levels of test.
Exercise
Write a plain Validator test that sends an OrderRequest with a valid customer id and one line whose quantity is 0, and asserts on the failing property path. What path do you expect, and which annotation on OrderRequest makes it appear?
Show answer
Validate new OrderRequest("c-1", List.of(new OrderLine("sku-1", 0))) and collect the property paths. The expected path is lines[0].quantity. It appears only because @Valid on the List<@Valid OrderLine> element type cascades validation into each line, and @Positive on quantity rejects 0. Without the cascade, the set of violations would be empty.