How it works...

Our User class uses four of the new constraints introduced by Jakarta Bean Validation 2.0:

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:

This is shown in the following code snippet:

User user = new User(
"elder",
"elder@eldermoraes.com",
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:

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.