SKILL.md--- name: unit-test-bean-validation description: Provides patterns for unit testing Jakarta Bean Validation (JSR-380), including @Valid, @NotNull, @Min, @Max, @Email constraints with Hibernate Validator. Generates custom validator tests, constraint violation assertions, validation groups, and parameterized validation tests. Validates data integrity logic without Spring context. Use when writing validation tests, bean validation tests, or testing custom constraint validators. allowed-tools: Read, Write, Bash, Glob, Grep --- # Unit Testing Jakarta Bean Validation ## Overview This skill provides executable patterns for unit testing Jakarta Bean Validation annotations and custom validators using JUnit 5. Covers built-in constraints (`@NotNull`, `@Email`, `@Min`, `@Max`, `@Size`), custom `@Constraint` implementations, cross-field validation, and validation groups. Tests run in isolation without Spring context. ## When to Use - Writing unit tests for Jakarta Bean Validation or JSR-380 constraints - Testing custom `@Constraint` validators and constraint violation messages - Testing bean validation logic in DTOs and request objects - Verifying cross-field validation (e.g., password matching) - Testing conditional validation with validation groups - Fast validation tests without Spring Boot context ## Instructions 1. **Add dependencies**: Include `jakarta.validation-api` and `hibernate-validator` in test scope 2. **Create base test class**: Build `Validator` once in `@BeforeEach` using `Validation.buildDefaultValidatorFactory()` 3. **Test valid cases first**: Verify objects pass without violations 4. **Test invalid cases**: Assert constraint violations include correct property path and message 5. **Extract violation details**: Use `getPropertyPath()`, `getMessage()`, `getInvalidValue()` 6. **Test custom validators**: See `references/custom-validators.md` for patterns 7. **Use parameterized tests**: Test multiple inputs efficiently with `@ParameterizedTest` 8. **Group validation tests**: Use validation groups for conditional rules (see `references/advanced-patterns.md`) ## Examples ### Maven Setup ```xml <dependency> <groupId>jakarta.validation</groupId> <artifactId>jakarta.validation-api</artifactId> </dependency> <dependency> <groupId>org.hibernate.validator</groupId> <artifactId>hibernate-validator</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.assertj</groupId> <artifactId>assertj-core</artifactId> <scope>test</scope> </dependency> ``` ### Common Test Setup ```java import jakarta.validation.*; import jakarta.validation.ConstraintViolation; import jakarta.validation.path.Path; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.*; class BaseValidationTest { protected Validator validator; @BeforeEach void setUpValidator() { validator = Validation.buildDefaultVal