JPAUnit - A replacement for DBUnit in JPA Unit Tests

JPAUnit is the result of several days of fighting with Hibernate's 4.3.10 JPA implementation and DBUnit trying to get the two to work together.

Eventually we gave up and decided to write our own library. How hard could it be right? :) Besides after several days of coding in circles around DBUnit it was nice to have a change.

JPAUnit - Light Weight JPA Unit Testing

The JPAUnit repository is on github. There are unit tests that hopefully explain how it works. We have already moved some of our projects over to JPAUnit and the results look promising. No need to leave the comfort zone of JPA to load your unit tests!

How Does JPAUnit Work?

JPAUnit can load DBUnit xml data sets. We didn't want to have to rewrite all those configuration files so we created a parser for DBUnit files.

<?xml version="1.0" encoding="UTF-8"?>
    <SimpleBigDecimalEntity id="1" bigDecimalValue="1000.24" />
    <SimpleBigDecimalEntity id="2" bigDecimalValue="999999999999.9999" />
    <ForeignEntity id="1" simpleBigDecimal_id="1"  stringValue="String Value" />

JPAUnit relies on Java naming conventions for much of its functionality. It expects all entities to expose their id (primary key) via "getId" which returns an int or Integer. It assumes the use of surrogate keys. JPAUnit's init method requires an data set file on the ClassPath, the package name to prepend to class names to find classes on the ClassPath, and an entity manager.

public class JpaLoaderForeignEntityTest {

    private static EntityManager em;
    private final String modelPackageName = "";

    public static void beforeClass() {
        em = Persistence.createEntityManagerFactory("jpaunittest").createEntityManager();

    public void foreignTest() throws ParserException {
        JpaLoader loader = new JpaLoader();
        loader.init("META-INF/foreignentity.xml", modelPackageName, new SaxHandler(), em);
        try {
            Query qry = em.createQuery("Select c from ForeignEntity c where c.stringValue=?");
            qry.setParameter(1,"String Value");
            ForeignEntity ent = (ForeignEntity) qry.getSingleResult();
            BigDecimal result = new BigDecimal("1000.24");
            Assert.assertTrue(MessageFormat.format("Expected {0} but got {1}",result,ent.getSimpleBigDecimal().getBigDecimalValue()),
        } finally {


Release 0.1?

We hope to release version 0.1 for Mandela Day 2015.