Our User class uses three of the new constraints introduced by Bean Validation 2.0:
- @NotBlank: Assures 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: Allows only a valid email format. Forget those crazy JavaScript functions!
- @NotEmpty: Ensures that a list has at least one item.
- @PositiveOrZero: Guarantees that a number is equal or greater than zero.
Then we create a test class (using JUnit) to test our validations. It first instantiates Validator:
@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:
- Name not empty
- Valid email
- profileId list only with integers greater than zero:
User user = new User(
"elder",
"elder@eldermoraes.com",
asList(1,2));
And finally, 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());
And the other methods work with variations around this model:
- 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.