Sub topic 14
Testing validation
This chapter assumes you can write JUnit 5 tests, you know the CreateUserRequest, UserController and ApiExceptionHandler classes from earlier chapters, and spring-boot-starter-test is on your test classpath.
Two levels of test
Validation rules can be tested at two levels, and each level catches different mistakes.
| Level | Tool | What it proves |
|---|---|---|
| Constraints only | Plain `Validator` | The annotations on a DTO accept and reject the right values |
| HTTP behavior | `@WebMvcTest` with `MockMvc` | `@Valid` is wired up and the error response has the shape clients expect |
flowchart TDTesting constraints with a plain Validator
A plain Validator test needs no Spring context, so it runs in milliseconds. You build the validator yourself and inspect the returned ConstraintViolation objects.
import static org.assertj.core.api.Assertions.assertThat;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import java.util.Set;
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();
}
@Test
void validRequestHasNoViolations() {
var request = new CreateUserRequest("Ada", "[email protected]", 30);
assertThat(validator.validate(request)).isEmpty();
}
@Test
void underageUserViolatesOnlyAge() {
var request = new CreateUserRequest("Ada", "[email protected]", 17);
Set<ConstraintViolation<CreateUserRequest>> violations = validator.validate(request);
assertThat(violations)
.extracting(v -> v.getPropertyPath().toString())
.containsExactly("age");
}
}Assert on the property path, not on the message text. Messages change when you externalize them, and paths do not.
Testing a custom constraint
Test a custom validator with a small holder record. Put the test in the same package as AllowedCountryValidator, because that class is package-private. Cover null explicitly, since the convention is that null is valid.
import static org.assertj.core.api.Assertions.assertThat;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import org.junit.jupiter.api.Test;
class AllowedCountryTest {
record Address(@AllowedCountry String country) {
}
private final Validator validator =
Validation.buildDefaultValidatorFactory().getValidator();
@Test
void acceptsSupportedAndNullCountries() {
assertThat(validator.validate(new Address("DE"))).isEmpty();
assertThat(validator.validate(new Address(null))).isEmpty();
}
@Test
void rejectsUnsupportedCountry() {
assertThat(validator.validate(new Address("XX"))).hasSize(1);
}
}Testing the HTTP contract with MockMvc
@WebMvcTest loads only the web layer. It also picks up @RestControllerAdvice beans, so your ApiExceptionHandler is active without extra configuration.
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 UserControllerValidationTest {
@Autowired
private MockMvc mockMvc;
@Test
void invalidBodyReturns400WithFieldErrors() throws Exception {
mockMvc.perform(post("/users")
.contentType(MediaType.APPLICATION_JSON)
.content("""
{"name":"","email":"not-an-email","age":17}
"""))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.detail").value("Validation failed"))
.andExpect(jsonPath("$.errors.name").exists())
.andExpect(jsonPath("$.errors.email").exists())
.andExpect(jsonPath("$.errors.age").exists());
}
@Test
void validBodyReturns201() throws Exception {
mockMvc.perform(post("/users")
.contentType(MediaType.APPLICATION_JSON)
.content("""
{"name":"Ada","email":"[email protected]","age":30}
"""))
.andExpect(status().isCreated());
}
}The first test fails if someone removes @Valid from the controller. A plain Validator test would still pass in that case, which is why you need both levels.
Common mistakes
- Testing only the invalid case. Always include one valid request, or a validator that rejects everything will pass your tests.
- Using
containson the full violation set. UsecontainsExactlyorhasSizeso an unexpected extra violation fails the test. - Forgetting a test for path variable violations. Without a
ConstraintViolationExceptionhandler, a request likeGET /orders/0returns 500 instead of 400.
Exercise
Why does the MockMvc test catch a missing @Valid on the controller parameter, while a plain Validator test does not?
Show answer
A plain Validator test calls the validator directly on the DTO, so it never involves the controller. A MockMvc test sends a real request through Spring MVC. Without @Valid, Spring skips validation and returns 201 instead of 400, so the test fails.