Our User class uses four of the new constraints introduced by Jakarta Bean Validation 2.0:
- @NotBlank: This ensures that the value is not null, empty, or an empty string (it trims the value before evaluation, to make sure there aren't spaces).
- @Email: This allows only a valid email format. Forget those crazy JavaScript functions!
- @NotEmpty: This ensures that a list has at least one item.
- @PositiveOrZero: This guarantees that a number is equal to or greater than zero.
Then, we create a test class (using JUnit) to test our validations. It first instantiates Validator, as follows:
@BeforeClass
public static void setUpClass() {
validator = Validation.buildDefaultValidatorFactory().getValidator();
}
Validator is an API that validates beans according to the constraints defined for them.
Our first test method tests a valid user, which is a User object that has the following:
- Name not empty
- Valid email
- A profileId list only with integers greater than zero
This is shown in the following code snippet:
User user = new User(
"elder",
"[email protected]",
asList(1,2));
And finally, we have the validation:
Set<ConstraintViolation<User>> cv = validator.validate(user);
The validate() method from Validator returns a set of constraint violations found, if any, or an empty set if there are no violations at all.
So, for a valid user, it should return an empty set:
assertTrue(cv.isEmpty());
For the other methods that work with variations around this model, we have the following:
- invalidName(): Uses an empty name
- invalidEmail(): Uses a malformed email
- invalidId(): Adds some negative numbers to the list
Note that the invalidId() method adds two negative numbers to the list:
asList(-1,-2,1,2));
So, we expect two constraint violations:
assertEquals(2, cv.size());
In other words, Validator checks not only the constraints violated, but how many times they are violated.