Automatic Unit Testing JPA + CDI + Bean Validation

Actually this is more automatic integration testing since the components are tied together.  I used Weld for my CDI, EclipseLink for my JPA and Hibernate Validator for my Bean Validation implementations and H2 for my in-memory test database.

TL;DR the code

Here’s the code for the BaseJpaCdiBeanValidationTest.

public abstract class BaseJpaTest {
    protected static EntityManager em;
    private static EntityManagerFactory emf;
    private static ValidatorFactory vf;
    private static Weld weld;

    @BeforeClass
    public static void setupInfrastructure() {
        weld = new Weld();
        final WeldContainer container = weld.initialize();
        final JpaProvider jpaProvider = container.select(JpaProvider.class).get();
        vf = Validation.buildDefaultValidatorFactory();
        final Map<String, Object> props = new HashMap<>();
        props.put("javax.persistence.bean.manager", container.getBeanManager());
        props.put("javax.persistence.schema-generation.database.action", "create");
        props.put("javax.persistence.jdbc.url", "jdbc:h2:mem:test");
        props.put("javax.persistence.jdbc.driver", "org.h2.Driver");
        emf = Persistence.createEntityManagerFactory("test-pu", props);
        em = emf.createEntityManager();
        jpaProvider.setEntityManager(em);
    }

    @AfterClass
    public static void tearDownInfrastructure() {
        em.close();
        emf.close();
        vf.close();
        weld.shutdown();
    }

    @Before
    public void beginTransaction() {
        em.getTransaction().begin();
    }
    @After
    public void rollbackTransaction() {
        em.getTransaction().rollback();
    }
}