Add validation module: Bean Validation on Spring Boot 4.2.0 with Hibernate Validator 9.1.6, built-in and custom constraints, groups, method validation, ProblemDetail errors, message i18n, JPA integration and tests, with real transcripts

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b4RzcCS5JCAgcxLz7T
This commit is contained in:
Claude
2026-12-05 16:18:03 +05:30
parent a95f042051
commit 417903fbc2
78 changed files with 2279 additions and 0 deletions
@@ -0,0 +1,133 @@
package com.ankurm.validation;
import jakarta.validation.UnexpectedTypeException;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import jakarta.validation.constraints.*;
import org.hibernate.validator.constraints.*;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Test;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
/** Every row of the article's cheat sheet is one line of output/01-constraint-cheatsheet.txt. */
class ConstraintCheatSheetTest {
static final ValidatorFactory FACTORY = Validation.buildDefaultValidatorFactory();
static final Validator VALIDATOR = FACTORY.getValidator();
@AfterAll
static void close() {
FACTORY.close();
}
static class Samples {
@NotNull String notNull;
@Null String isNull;
@NotEmpty String notEmpty;
@NotBlank String notBlank;
@AssertTrue Boolean assertTrue;
@AssertFalse Boolean assertFalse;
@Size(min = 2, max = 4) String size;
@Min(10) Integer min;
@Max(10) Integer max;
@DecimalMin(value = "0.0", inclusive = false) BigDecimal decimalMin;
@DecimalMax("99.99") BigDecimal decimalMax;
@Digits(integer = 3, fraction = 2) BigDecimal digits;
@Positive Integer positive;
@PositiveOrZero Integer positiveOrZero;
@Negative Integer negative;
@NegativeOrZero Integer negativeOrZero;
@Past LocalDate past;
@PastOrPresent LocalDate pastOrPresent;
@Future LocalDate future;
@FutureOrPresent LocalDate futureOrPresent;
@Pattern(regexp = "[A-Z]{3}") String pattern;
@Email String email;
// Hibernate Validator extras (org.hibernate.validator.constraints)
@Length(min = 2, max = 4) String length;
@Range(min = 1, max = 5) Integer range;
@URL String url;
@UUID String uuid;
@CreditCardNumber String creditCard;
@UniqueElements List<String> unique;
@IpAddress String ip;
}
record Probe(String property, Object value) { }
@Test
void cheatSheet() {
Transcript t = new Transcript("01-constraint-cheatsheet");
LocalDate today = LocalDate.now();
List<Probe> probes = List.of(
new Probe("notNull", ""), new Probe("isNull", ""),
new Probe("notEmpty", " "), new Probe("notEmpty", ""),
new Probe("notBlank", " "), new Probe("assertTrue", false), new Probe("assertFalse", true),
new Probe("size", "abcde"), new Probe("min", 9), new Probe("max", 11),
new Probe("decimalMin", new BigDecimal("0.0")), new Probe("decimalMax", new BigDecimal("100")),
new Probe("digits", new BigDecimal("1.234")), new Probe("positive", 0),
new Probe("positiveOrZero", -1), new Probe("negative", 0), new Probe("negativeOrZero", 1),
new Probe("past", today), new Probe("pastOrPresent", today.plusDays(1)),
new Probe("future", today), new Probe("futureOrPresent", today.minusDays(1)),
new Probe("pattern", "ABCD"), new Probe("email", "not-an-email"), new Probe("email", "a@b"),
new Probe("email", ""), new Probe("length", "abcde"), new Probe("range", 6),
new Probe("url", "ankurm.com"), new Probe("uuid", "1234"),
new Probe("creditCard", "4111111111111112"), new Probe("unique", List.of("a", "a")),
new Probe("ip", "999.1.1.1"));
t.head("a sample value for each constraint (property: value -> result)");
for (Probe p : probes) {
var v = VALIDATOR.validateValue(Samples.class, p.property(), p.value());
String shown = p.value() instanceof LocalDate d
? (d.equals(today) ? "today" : d.isAfter(today) ? "tomorrow" : "yesterday")
: p.value() instanceof String s ? "\"" + s + "\"" : String.valueOf(p.value());
String msg = v.isEmpty() ? "valid" : v.iterator().next().getMessage();
t.line(String.format("%-16s %-20s %s", p.property(), shown, msg));
}
t.head("which constraints reject null? (every other field left null)");
var onNull = VALIDATOR.validate(new Samples());
onNull.stream().map(v -> v.getPropertyPath().toString()).sorted()
.forEach(name -> t.line("rejects null: " + name));
t.write();
assertThat(onNull).extracting(v -> v.getPropertyPath().toString())
.containsExactlyInAnyOrder("notNull", "notEmpty", "notBlank");
}
static class Mistake {
@Size(min = 1) Integer quantity = 5;
}
static class NotBlankOnNumber {
@NotBlank Integer quantity = 5;
}
record Pin(@Email(regexp = ".+@.+..+") String loose, @Email(regexp = ".+@.+\\..+") String strict) { }
record Age(@Positive @Min(18) int age) { }
@Test
void mistakes() {
Transcript t = new Transcript("02-constraint-mistakes");
t.head("@Size on an Integer compiles, and fails when first validated");
assertThatThrownBy(() -> VALIDATOR.validate(new Mistake()))
.isInstanceOf(UnexpectedTypeException.class)
.satisfies(e -> t.line(e.getClass().getName()).line(e.getMessage()));
t.head("@NotBlank on an Integer");
assertThatThrownBy(() -> VALIDATOR.validate(new NotBlankOnNumber()))
.satisfies(e -> t.line(e.getMessage()));
t.head("an unescaped dot in @Email(regexp): value a@bcom");
t.line(Transcript.show(VALIDATOR.validate(new Pin("a@bcom", "a@bcom"))));
t.head("@Positive plus @Min(18) on age = -1 reports both");
t.line(Transcript.show(VALIDATOR.validate(new Age(-1))));
t.write();
}
}
@@ -0,0 +1,120 @@
package com.ankurm.validation;
import com.ankurm.validation.constraint.CaseCheck;
import com.ankurm.validation.model.Address;
import com.ankurm.validation.model.Booking;
import com.ankurm.validation.model.ContactForm;
import com.ankurm.validation.model.PasswordChange;
import com.ankurm.validation.model.UserRequest;
import jakarta.validation.Valid;
import jakarta.validation.Validation;
import jakarta.validation.ValidationException;
import jakarta.validation.Validator;
import jakarta.validation.constraints.NotBlank;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.time.LocalDate;
import java.util.List;
import java.util.Locale;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@SpringBootTest
class CustomConstraintTest {
@Autowired
Validator validator; // Spring Boot's auto-configured bean
record Code(@CaseCheck String upper, @CaseCheck(CaseCheck.CaseMode.LOWER) String lower) { }
record Item(@NotBlank String name) { }
record WithValid(@Valid Item item) { }
record WithoutValid(Item item) { }
record ElementValid(List<@Valid Item> items) { }
record ContainerValid(@Valid List<Item> items) { }
/** A composed constraint whose @Target omits RECORD_COMPONENT on purpose. */
@java.lang.annotation.Target(java.lang.annotation.ElementType.FIELD)
@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@jakarta.validation.Constraint(validatedBy = {})
@NotBlank
@interface FieldOnlyRequired {
String message() default "required";
Class<?>[] groups() default {};
Class<? extends jakarta.validation.Payload>[] payload() default {};
}
record FieldOnly(@FieldOnlyRequired String name) { }
static UserRequest user(String name, Address address) {
return new UserRequest(name, "[email protected]", 30, List.of("dev"), address);
}
@Test
void customConstraints() {
Transcript t = new Transcript("03-custom-constraints");
t.head("@CaseCheck(UPPER) \"abc\", @CaseCheck(LOWER) \"abc\"");
t.line(Transcript.show(validator.validate(new Code("abc", "abc"))));
t.head("a null value passes the custom rule");
t.line(Transcript.show(validator.validate(new Code(null, null))));
t.head("short spam message");
t.line(Transcript.show(validator.validate(new ContactForm("[email protected]", "This is spam."))));
t.head("long message containing spam");
t.line(Transcript.show(validator.validate(new ContactForm("[email protected]",
"This message mentions spam but is long enough to be taken seriously."))));
t.head("a composed constraint with @Target(FIELD) only, used on a record component");
t.line(Transcript.show(validator.validate(new FieldOnly(" "))));
t.head("validator with a constructor-injected bean, username admin");
t.line(Transcript.show(validator.validate(user("admin", new Address("Mumbai", "400703")))));
t.head("same object, validator built by hand without Spring");
try (var factory = Validation.buildDefaultValidatorFactory()) {
assertThatThrownBy(() -> factory.getValidator().validate(user("admin", new Address("Mumbai", "400703"))))
.isInstanceOf(ValidationException.class)
.satisfies(e -> t.line(e.getClass().getSimpleName() + ": " + e.getMessage()));
}
t.write();
}
@Test
void nesting() {
Transcript t = new Transcript("04-nested-and-containers");
Item bad = new Item("");
t.head("nested object with @Valid");
t.line(Transcript.show(validator.validate(new WithValid(bad))));
t.head("nested object without @Valid");
t.line(Transcript.show(validator.validate(new WithoutValid(bad))));
t.head("List<@Valid Item>");
t.line(Transcript.show(validator.validate(new ElementValid(List.of(new Item("ok"), bad)))));
t.head("@Valid List<Item>");
t.line(Transcript.show(validator.validate(new ContainerValid(List.of(new Item("ok"), bad)))));
t.head("List<@NotBlank String> and a nested record, all wrong");
t.line(Transcript.show(validator.validate(new UserRequest("ravi", "[email protected]", 30,
List.of("dev", " "), new Address("", "4007")))));
t.write();
}
@Test
void crossField() {
Transcript t = new Transcript("05-cross-field");
t.head("@DateRange moves its violation onto endDate");
var range = validator.validate(new Booking(LocalDate.of(2026, 5, 10), LocalDate.of(2026, 5, 1)));
t.line(Transcript.show(range));
t.head("@DateRange with a missing date: only @NotNull speaks");
t.line(Transcript.show(validator.validate(new Booking(LocalDate.of(2026, 5, 10), null))));
t.head("@PasswordsMatch keeps the default object-level violation");
t.line(Transcript.show(validator.validate(new PasswordChange("correct-horse", "wrong-horse"))));
t.head("class-level constraint while a field is also invalid");
t.line(Transcript.show(validator.validate(new PasswordChange("short", "other"))));
t.write();
assertThat(range).extracting(v -> v.getPropertyPath().toString()).containsExactly("endDate");
}
}
@@ -0,0 +1,31 @@
package com.ankurm.validation;
import com.ankurm.validation.model.Booking;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.time.LocalDate;
import static org.assertj.core.api.Assertions.assertThat;
/** No Spring: the fastest way to test a constraint is through a real Validator. */
class DateRangeValidatorUnitTest {
static final ValidatorFactory FACTORY = Validation.buildDefaultValidatorFactory();
static final Validator VALIDATOR = FACTORY.getValidator();
@AfterAll
static void close() {
FACTORY.close();
}
@ParameterizedTest
@CsvSource({"2026-05-01, 2026-05-10, 0", "2026-05-10, 2026-05-01, 1", "2026-05-01, 2026-05-01, 1"})
void endMustBeAfterStart(LocalDate start, LocalDate end, int violations) {
assertThat(VALIDATOR.validate(new Booking(start, end))).hasSize(violations);
}
}
@@ -0,0 +1,50 @@
package com.ankurm.validation;
import jakarta.validation.Constraint;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import jakarta.validation.Payload;
import jakarta.validation.Validation;
import org.junit.jupiter.api.Test;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/** User input concatenated into a violation template: what gets interpreted? */
class ElInjectionTest {
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = Echo.class)
@interface Unknown {
String message() default "unknown";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
int secret() default 42;
}
public static class Echo implements ConstraintValidator<Unknown, String> {
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate("unknown code: " + value).addConstraintViolation();
return false;
}
}
record Input(@Unknown String code) { }
@Test
void userInputInTemplates() {
Transcript t = new Transcript("16-template-injection");
try (var factory = Validation.buildDefaultValidatorFactory()) {
for (String attack : new String[] {"${7*7}", "{secret}", "{jakarta.validation.constraints.NotNull.message}"}) {
t.head("input " + attack);
t.line(Transcript.show(factory.getValidator().validate(new Input(attack))));
}
}
t.write();
}
}
@@ -0,0 +1,58 @@
package com.ankurm.validation;
import com.ankurm.validation.model.Groups.CheapThenExpensive;
import com.ankurm.validation.model.Groups.Expensive;
import com.ankurm.validation.model.Groups.OnCreate;
import com.ankurm.validation.model.Groups.OnUpdate;
import com.ankurm.validation.model.Groups.Update;
import com.ankurm.validation.model.ProductRequest;
import jakarta.validation.Valid;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import jakarta.validation.groups.ConvertGroup;
import jakarta.validation.groups.Default;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class GroupsTest {
record Signup(@NotBlank String name, @Size(min = 8, groups = Expensive.class) String password) { }
record Line(@NotNull(groups = OnUpdate.class) Long id) { }
record Plain(@Valid Line line) { }
record Converted(@Valid @ConvertGroup(from = Default.class, to = OnUpdate.class) Line line) { }
@Test
void groups() {
try (var factory = Validation.buildDefaultValidatorFactory()) {
Validator v = factory.getValidator();
Transcript t = new Transcript("06-groups");
ProductRequest bad = new ProductRequest(null, " ", -5);
t.head("new ProductRequest(id=null, name=\" \", price=-5)");
t.line("validate(p) " + Transcript.show(v.validate(bad)));
t.line("validate(p, OnCreate) " + Transcript.show(v.validate(bad, OnCreate.class)));
t.line("validate(p, OnUpdate) " + Transcript.show(v.validate(bad, OnUpdate.class)));
t.line("validate(p, Default, OnUpdate) " + Transcript.show(v.validate(bad, Default.class, OnUpdate.class)));
t.line("validate(p, Update extends Default) " + Transcript.show(v.validate(bad, Update.class)));
t.head("@GroupSequence({Default, Expensive}): name blank, password short");
t.line(Transcript.show(v.validate(new Signup("", "abc"), CheapThenExpensive.class)));
t.head("same sequence once the name is fixed");
t.line(Transcript.show(v.validate(new Signup("ravi", "abc"), CheapThenExpensive.class)));
t.head("cascade: nested rule is in OnUpdate, parent validated with Default");
t.line("@Valid " + Transcript.show(v.validate(new Plain(new Line(null)))));
t.line("@Valid @ConvertGroup " + Transcript.show(v.validate(new Converted(new Line(null)))));
t.write();
assertThat(v.validate(bad, OnCreate.class)).hasSize(1);
assertThat(v.validate(bad)).hasSize(1);
}
}
}
@@ -0,0 +1,42 @@
package com.ankurm.validation;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
/** Real HTTP against the embedded Tomcat, so error dispatch to /error happens as in production. */
final class Http {
private final HttpClient client = HttpClient.newHttpClient();
private final String base;
private final Transcript t;
Http(int port, Transcript t) {
this.base = "http://localhost:" + port;
this.t = t;
}
int send(String method, String path, String json, String... headers) {
try {
var b = HttpRequest.newBuilder(URI.create(base + path));
b.method(method, json == null ? HttpRequest.BodyPublishers.noBody()
: HttpRequest.BodyPublishers.ofString(json));
if (json != null) {
b.header("Content-Type", "application/json");
}
for (int i = 0; i < headers.length; i += 2) {
b.header(headers[i], headers[i + 1]);
}
var r = client.send(b.build(), HttpResponse.BodyHandlers.ofString());
t.head(method + " " + path + (json == null ? "" : " " + json)
+ (headers.length == 0 ? "" : " [" + headers[0] + ": " + headers[1] + "]"));
t.line("HTTP " + r.statusCode() + " " + r.headers().firstValue("Content-Type").orElse("(no content type)"));
t.line(r.body().isEmpty() ? "(empty body)"
: r.body().replaceAll("\"timestamp\":\"[^\"]+\"", "\"timestamp\":\"...\""));
return r.statusCode();
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
}
@@ -0,0 +1,101 @@
package com.ankurm.validation;
import com.ankurm.validation.jpa.Account;
import com.ankurm.validation.jpa.Note;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.Validator;
import org.hibernate.Hibernate;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.function.Consumer;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
@SpringBootTest
class JpaIntegrationTest {
@Autowired
EntityManagerFactory emf;
@Autowired
JdbcTemplate jdbc;
@Autowired
Validator validator;
private void tx(Consumer<EntityManager> work) {
try (EntityManager em = emf.createEntityManager()) {
var tx = em.getTransaction();
tx.begin();
try {
work.accept(em);
tx.commit();
} catch (RuntimeException e) {
if (tx.isActive()) {
tx.rollback();
}
throw e;
}
}
}
private static void report(Transcript t, Throwable e) {
Throwable c = e;
while (c != null && !(c instanceof ConstraintViolationException)) {
c = c.getCause();
}
t.line(e.getClass().getName());
if (c != null) {
((ConstraintViolationException) c).getConstraintViolations().stream()
.map(v -> " " + v.getPropertyPath() + ": " + v.getMessage()).sorted().forEach(t::line);
}
}
@Test
void hibernateOrmIntegration() {
Transcript t = new Transcript("17-jpa-integration");
t.head("generated columns of ACCOUNT (H2 information_schema)");
jdbc.queryForList("select column_name, data_type, character_maximum_length, is_nullable "
+ "from information_schema.columns where table_name = 'ACCOUNT' order by column_name")
.forEach(r -> t.line(r.get("column_name") + " " + r.get("data_type") + " length="
+ r.get("character_maximum_length") + " nullable=" + r.get("is_nullable")));
t.head("check constraints on ACCOUNT");
jdbc.queryForList("select cc.check_clause from information_schema.check_constraints cc "
+ "join information_schema.table_constraints tc on tc.constraint_name = cc.constraint_name "
+ "where tc.table_name = 'ACCOUNT' order by 1", String.class)
.forEach(t::line);
t.head("persist(new Account(null, 15))");
Throwable persist = catchThrowable(() -> tx(em -> em.persist(new Account(null, 15))));
report(t, persist);
t.line("rows in ACCOUNT: " + jdbc.queryForObject("select count(*) from account", Integer.class));
long[] id = new long[1];
tx(em -> {
Account a = new Account("ravi", 30);
a.getNotes().add(new Note(a, "first"));
em.persist(a);
em.flush();
id[0] = a.getId();
});
t.head("load, setAge(10), commit (no save or merge call)");
report(t, catchThrowable(() -> tx(em -> em.find(Account.class, id[0]).setAge(10))));
t.head("validate a loaded entity whose lazy List<@Valid Note> is untouched");
tx(em -> {
Account a = em.find(Account.class, id[0]);
t.line("notes initialised before: " + Hibernate.isInitialized(a.getNotes()));
t.line(Transcript.show(validator.validate(a)));
t.line("notes initialised after: " + Hibernate.isInitialized(a.getNotes()));
});
t.write();
assertThat(persist).isNotNull();
}
}
@@ -0,0 +1,46 @@
package com.ankurm.validation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.Size;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.i18n.LocaleContextHolder;
import java.util.Locale;
@SpringBootTest
class MessagesTest {
record Msg(@Min(value = 18, message = "{user.age.min}") int age,
@Min(value = 18, message = "{vm.only}") int other,
@Min(value = 18, message = "{no.such.key}") int missing,
@Min(value = 18, message = "got ${validatedValue}, need {value}") int el,
@Size(min = 3) String builtIn) { }
@Autowired
Validator springValidator;
@Test
void whereMessagesComeFrom() {
Transcript t = new Transcript("15-message-sources");
Msg bad = new Msg(15, 15, 15, 15, "a");
t.head("Spring Boot validator, locale en");
LocaleContextHolder.setLocale(Locale.ENGLISH);
springValidator.validate(bad).stream().map(v -> v.getPropertyPath() + ": " + v.getMessage())
.sorted().forEach(t::line);
t.head("Spring Boot validator, locale fr");
LocaleContextHolder.setLocale(Locale.FRENCH);
springValidator.validate(bad).stream().map(v -> v.getPropertyPath() + ": " + v.getMessage())
.sorted().forEach(t::line);
LocaleContextHolder.resetLocaleContext();
t.head("plain Validation.buildDefaultValidatorFactory(), JVM locale en");
try (var factory = Validation.buildDefaultValidatorFactory()) {
factory.getValidator().validate(bad).stream().map(v -> v.getPropertyPath() + ": " + v.getMessage())
.sorted().forEach(t::line);
}
t.write();
}
}
@@ -0,0 +1,30 @@
package com.ankurm.validation;
import com.ankurm.validation.service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.validation.method.MethodValidationException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
@SpringBootTest(properties = "spring.validation.method.adapt-constraint-violations=true")
class MethodValidationAdaptedTest {
@Autowired
UserService service;
@Test
void adapted() {
Transcript t = new Transcript("08-method-validation-adapted");
t.head("spring.validation.method.adapt-constraint-violations=true, createUser(good, \"\")");
Throwable e = catchThrowable(() -> service.createUser(MethodValidationTest.GOOD, ""));
t.line(e.getClass().getName());
((MethodValidationException) e).getParameterValidationResults().forEach(r ->
r.getResolvableErrors().forEach(err -> t.line(" "
+ r.getMethodParameter().getParameterName() + ": " + err.getDefaultMessage())));
t.write();
assertThat(e).isInstanceOf(MethodValidationException.class);
}
}
@@ -0,0 +1,91 @@
package com.ankurm.validation;
import com.ankurm.validation.model.Address;
import com.ankurm.validation.model.UserRequest;
import com.ankurm.validation.service.UserService;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.constraints.NotNull;
import org.assertj.core.api.ThrowableAssert.ThrowingCallable;
import org.junit.jupiter.api.Test;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.validation.annotation.Validated;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
@SpringBootTest
@Import(MethodValidationTest.Extra.class)
class MethodValidationTest {
interface Greeter {
String greet(String name);
}
/** Adds a parameter constraint the interface does not declare. Not allowed. */
@Validated
static class StricterGreeter implements Greeter {
@Override
public String greet(@NotNull String name) {
return "hi " + name;
}
}
@TestConfiguration
static class Extra {
@Bean
Greeter greeter() {
return new StricterGreeter();
}
}
@Autowired
UserService service;
@Autowired
Greeter greeter;
static final UserRequest GOOD = new UserRequest("ravi", "[email protected]", 30, List.of("dev"),
new Address("Mumbai", "400703"));
static void report(Transcript t, ThrowingCallable call) {
Throwable e = catchThrowable(call);
if (e == null) {
t.line("no exception");
return;
}
t.line(e.getClass().getName());
if (e instanceof ConstraintViolationException cve) {
cve.getConstraintViolations().stream()
.map(v -> " " + v.getPropertyPath() + ": " + v.getMessage())
.sorted().forEach(t::line);
} else {
t.line(" " + e.getMessage().lines().findFirst().orElse(""));
}
}
@Test
void methodValidation() {
Transcript t = new Transcript("07-method-validation");
t.line("service is an AOP proxy: " + AopUtils.isAopProxy(service));
t.head("createUser(good, \"\")");
report(t, () -> service.createUser(GOOD, ""));
t.head("createUser(null, \"token\")");
report(t, () -> service.createUser(null, "token"));
t.head("displayName(0) - the RETURN value is invalid");
report(t, () -> service.displayName(0L));
t.head("createViaThis(good) - calls createUser(user, \"\") on this");
report(t, () -> t.line("returned: " + service.createViaThis(GOOD)));
t.head("implementation adds @NotNull that the interface lacks");
report(t, () -> greeter.greet("x"));
t.write();
assertThat(catchThrowable(() -> service.createUser(GOOD, "")))
.isInstanceOf(ConstraintViolationException.class);
}
}
@@ -0,0 +1,33 @@
package com.ankurm.validation;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.assertj.MockMvcTester;
import static org.assertj.core.api.Assertions.assertThat;
/** The same default request as in 09-http-defaults, through MockMvc: no servlet error dispatch. */
@SpringBootTest(properties = "app.problem-advice=false")
@AutoConfigureMockMvc
class MockMvcEmptyBodyTest {
@Autowired
MockMvcTester mvc;
@Test
void bodyIsEmptyInMockMvc() throws Exception {
var result = mvc.post().uri("/contacts").contentType(MediaType.APPLICATION_JSON)
.content(WebDefaultsTest.SPAM).exchange();
String body = result.getResponse().getContentAsString();
Transcript t = new Transcript("18-mockmvc-vs-server");
t.head("MockMvc, no advice, POST /contacts with the short spam message");
t.line("status: " + result.getResponse().getStatus());
t.line("body length: " + body.length());
t.line("resolved exception: " + result.getMvcResult().getResolvedException().getClass().getSimpleName());
t.write();
assertThat(body).isEmpty();
}
}
@@ -0,0 +1,59 @@
package com.ankurm.validation;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ProblemAdviceTest {
static final String BAD_USER = "{\"username\":\"admin\",\"email\":\"nope\",\"age\":15,\"roles\":[\"dev\"],"
+ "\"address\":{\"city\":\"Mumbai\",\"pinCode\":\"4007\"}}";
@LocalServerPort
int port;
@Test
void oneShapeForEveryFailure() {
Transcript t = new Transcript("11-http-problem-advice");
Http http = new Http(port, t);
http.send("POST", "/users", BAD_USER);
http.send("GET", "/users?size=0&sort=name", null);
http.send("POST", "/contacts/bulk", "[{\"email\":\"[email protected]\",\"message\":\"This is spam.\"}]");
http.send("POST", "/password", "{\"password\":\"correct-horse\",\"confirmation\":\"nope\"}");
http.send("POST", "/users/internal", "{}");
http.send("POST", "/bookings", "{\"startDate\":\"2026-05-10\",\"endDate\":\"2026-05-01\"}");
http.send("POST", "/bookings", "{\"startDate\":\"10/05/2026\"}");
t.write();
}
@Test
void groupsOverHttp() {
Transcript t = new Transcript("12-http-groups");
Http http = new Http(port, t);
http.send("POST", "/products", "{\"id\":7,\"name\":\"Pen\",\"price\":10}");
http.send("PUT", "/products", "{\"name\":\"Pen\",\"price\":-1}");
http.send("PUT", "/products", "{\"id\":7,\"name\":\"Pen\",\"price\":10}");
t.write();
}
@Test
void bindingResultPattern() {
Transcript t = new Transcript("13-http-bindingresult-pitfalls");
Http http = new Http(port, t);
http.send("POST", "/old/contact", "{\"email\":\"[email protected]\",\"message\":\"This is spam.\"}");
http.send("POST", "/old/contact", "{\"email\":\"[email protected]\",\"message\":\"\"}");
http.send("POST", "/old/password", "{\"password\":\"correct-horse\",\"confirmation\":\"nope\"}");
t.write();
}
@Test
void localised() {
Transcript t = new Transcript("14-http-i18n");
Http http = new Http(port, t);
http.send("POST", "/users", BAD_USER, "Accept-Language", "en");
http.send("POST", "/users", BAD_USER, "Accept-Language", "fr");
http.send("GET", "/users?size=0&sort=name", null, "Accept-Language", "fr");
t.write();
}
}
@@ -0,0 +1,22 @@
package com.ankurm.validation;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
properties = {"app.problem-advice=false", "spring.mvc.problemdetails.enabled=true"})
class ProblemDetailsPropertyTest {
@LocalServerPort
int port;
@Test
void propertyOnly() {
Transcript t = new Transcript("10-http-problemdetails-property");
Http http = new Http(port, t);
http.send("POST", "/contacts", WebDefaultsTest.SPAM);
http.send("GET", "/users?size=0&sort=name", null);
t.write();
}
}
@@ -0,0 +1,54 @@
package com.ankurm.validation;
import jakarta.validation.ConstraintViolation;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Set;
/** Collects the lines a test observed and writes them to output/NN-name.txt. */
final class Transcript {
private final Path file;
private final StringBuilder text = new StringBuilder();
Transcript(String name) {
this.file = Path.of("output", name + ".txt");
}
Transcript line(String s) {
text.append(s).append('\n');
return this;
}
Transcript head(String s) {
if (!text.isEmpty()) {
text.append('\n');
}
return line("== " + s);
}
void write() {
try {
Files.createDirectories(file.getParent());
Files.writeString(file, text.toString());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
/** Violations as "path: message" in a stable order. */
static <T> String show(Set<ConstraintViolation<T>> violations) {
if (violations.isEmpty()) {
return "(no violations)";
}
return violations.stream()
.map(v -> (v.getPropertyPath().toString().isEmpty() ? "<object>" : v.getPropertyPath().toString())
+ ": " + v.getMessage())
.sorted()
.reduce((a, b) -> a + " | " + b)
.orElseThrow();
}
}
@@ -0,0 +1,50 @@
package com.ankurm.validation;
import com.ankurm.validation.constraint.AvailableUsernameValidator;
import com.ankurm.validation.service.UserService;
import com.ankurm.validation.service.UsernameRegistry;
import com.ankurm.validation.web.UserController;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.assertj.MockMvcTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
/** A web slice: real controller, real validator, real advice, mocked collaborators. */
@WebMvcTest(UserController.class)
class ValidationSliceTest {
@Autowired
MockMvcTester mvc;
@MockitoBean
UserService service;
@MockitoBean
UsernameRegistry registry; // the custom validator's dependency
@Test
void takenUsernameIsReportedOnTheUsernameField() {
given(registry.isTaken("ravi")).willReturn(true);
assertThat(mvc.post().uri("/users").contentType(MediaType.APPLICATION_JSON).content("""
{"username":"ravi","email":"[email protected]","age":30,"roles":["dev"],
"address":{"city":"Mumbai","pinCode":"400703"}}
"""))
.hasStatus(400)
.bodyJson()
.extractingPath("$.errors[0].code").isEqualTo("AvailableUsername");
}
@Test
void parameterConstraintIsEnforcedInTheSliceToo() {
assertThat(mvc.get().uri("/users?size=500&sort=name"))
.hasStatus(400)
.bodyJson()
.extractingPath("$.errors[0].field").isEqualTo("size");
}
}
@@ -0,0 +1,32 @@
package com.ankurm.validation;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
import static org.assertj.core.api.Assertions.assertThat;
/** What you get with no @RestControllerAdvice of your own. */
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
properties = "app.problem-advice=false")
class WebDefaultsTest {
static final String SPAM = "{\"email\":\"[email protected]\",\"message\":\"This is spam.\"}";
@LocalServerPort
int port;
@Test
void bare() {
Transcript t = new Transcript("09-http-defaults");
Http http = new Http(port, t);
int body = http.send("POST", "/contacts", SPAM);
int param = http.send("GET", "/users?size=0&sort=name", null);
int list = http.send("POST", "/contacts/bulk", "[" + SPAM + "]");
int legacy = http.send("GET", "/legacy?size=0", null);
int service = http.send("POST", "/users/internal", "{}");
t.write();
assertThat(new int[] {body, param, list}).containsOnly(400);
assertThat(new int[] {legacy, service}).containsOnly(500);
}
}