Unit / Integration Testing the Bean Validation (JSR-303)
First you will need to load both: the Bean Validation andELSPIs. Hibernate Validator is the Reference Implementation (RI) for Bean Validation, and GlassFish implements the EL JSR:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.1.2.Final</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
<version>3.0.0</version>
<scope>test</scope>
</dependency>
Hibernate Validator requires Expression Language dependency. Without the javax.el dependency you will get the following error:
Caused by: javax.validation.ValidationException: HV000183: Unable to load 'javax.el.ExpressionFactory'. Check that you have the EL dependencies on the classpath
at org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.
(ResourceBundleMessageInterpolator.java:172)
at org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.
(ResourceBundleMessageInterpolator.java:118)
Now you are ready to launch your Integration Test:
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
public class ValidationTest {
private Validator validator;
@Before
public void init() {
ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
this.validator = vf.getValidator();
}
@Test
public void prereqsMet() {
Workshop validWorkshop = new Workshop(2, 2, true, 3);
Set<ConstraintViolation<Workshop>> violations = this.validator.validate(validWorkshop);
assertTrue(violations.isEmpty());
}
}
Strictly speaking it is not a unit test, rather an Integration Test. In Unit Test you would like to test the validator logic only, without any dependencies to the SPI.
See you at Java EE Workshops at MUC Airport , especially at the Java EE 7 / Java 8 Testing day!
Posted at11:37AM Sep 15, 2014byAdam Bienin Real World Java EE Patterns - Rethinking Best Practices | Comments[0]| Views/Hits: 0
Special Events: Java 8 with Java EE 7: "More Power with Less Code", 13th October, 2014 and Java EE 7: "Testing and Code Quality", 14th October, 2014