adam bien's blog

Rulz: EntityManager Provider for Integration Tests 📎

I used EntityManager initialization for an integration test as a possible use case for JUnit Rule during the recent Continuous Java EE 7 Testing, Deployment and Code Quality workshop:



import static com.airhacks.rulz.em.EntityManagerProvider.persistenceUnit;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import static org.junit.Assert.assertNotNull;
import org.junit.Rule;
import org.junit.Test;


public class WorkshopTest {

    @Rule
    public EntityManagerProvider emProvider = persistenceUnit("it");

    @Test
    public void crud() {
        EntityManager em = emProvider.em();
        assertNotNull(em);
        EntityTransaction tx = emProvider.tx();
        assertNotNull(tx);
        tx.begin();
        em.merge(new Workshop("Testing", "test what matters));
        tx.commit();
    }
}

I noticed, the code is reusable, so I extracted the rule and created the open source project: Rulz and pushed the library into maven central:


<dependency>
    <groupId>com.airhacks.rulz</groupId>
    <artifactId>em</artifactId>
	<version>[RECENT_VERSION]</version>
    <scope>test</scope>
</dependency>

A JUnit Rule is an alternative to inheritance, which I used so far: BCE Archetype.

See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting