This topic has not yet been written. The content below is from the topic description.
1.3. Validating constraints To perform a validation of these constraints, we use a Validator instance. Let's have a look at the CarTest class: Example 1.4. Class CarTest showing validation examples package com.mycompany; import static org.junit.Assert.*; import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; import org.junit.BeforeClass; import org.junit.Test; public class CarTest { private static Validator validator; @BeforeClass public static void setUp() { ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); validator = factory.getValidator(); } @Test public void manufacturerIsNull() { Car car = new Car(null, "DD-AB-123", 4); Set > constraintViolations = validator.validate(car); assertEquals(1, constraintViolations.size()); assertEquals("may not be null", constraintViolations.iterator().next().getMessage()); } @Test public void licensePlateTooShort() { Car car = new Car("Morris", "D", 4); Set> constraintViolations = validator.validate(car); assertEquals(1, constraintViolations.size()); assertEquals("size must be between 2 and 14", constraintViolations.iterator().next().getMessage()); } @Test public void seatCountTooLow() { Car car = new Car("Morris", "DD-AB-123", 1); Set> constraintViolations = validator.validate(car); assertEquals(1, constraintViolations.size()); assertEquals("must be greater than or equal to 2", constraintViolations.iterator().next().getMessage()); } @Test public void carIsValid() { Car car = new Car("Morris", "DD-AB-123", 2); Set> constraintViolations = validator.validate(car); assertEquals(0, constraintViolations.size()); } } In the setUp() method we get a Validator instance from the ValidatorFactory. A Validator instance is thread-safe and may be reused multiple times. For this reason we store it as field of our test class. We can use the Validator now to validate the different car instances in the test methods. The validate() method returns a set of ConstraintViolation instances, which we can iterate in order to see which validation errors occurred. The first three test methods show some expected constraint violations: The @NotNull constraint on manufacturer is violated in manufacturerIsNull() The @Size constraint on licensePlate is violated in licensePlateTooShort() The @Min constraint on seatCount is violated in seatCountTooLow() If the object validates successfully, validate() returns an empty set. Note that we only use classes from the package javax.validation from the Bean Validation API. As we don't reference any classes of the RI directly, it would be no problem to switch to another implementation of the API, should that need arise.