Search code examples
javahibernateunit-testingdaoderby

Unit Testing database layer DAO with derby in memory


I want to unit tests my DAO implementation with this:

public class BaseDAOImplTest {

    private EntityManagerFactory emFactory;
    private EntityManager em;
    private static Logger logger = Logger.getLogger(BaseDAOImplTest.class
            .getName());

    @Before
    public void setUp() throws SQLException, ClassNotFoundException {

        logger.info("Starting in-memory database for unit tests");

        try {

            //Creating testDB database
            Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
            DriverManager.getConnection("jdbc:derby:memory:TestingDB;create=true");
            logger.info("Building JPA EntityManager for unit tests");

            //Creating Entity Manager
            emFactory = Persistence.createEntityManagerFactory("TestingDB");
            em = emFactory.createEntityManager();
        } catch (ClassNotFoundException e) {

            e.printStackTrace();
        }
    }

    @Test
    public void testPersistExcursion() {
        BaseDAOImpl baseDao = new BaseDAOImpl(Excursion.class, em);
        Calendar c = Calendar.getInstance();
        c.set(2013, 8, 24);
        Excursion ex1 = createExcursion(c.getTime(), 10, "Simple excursion 1", "New York", 35);
        ex1 = baseDao.persist(ex1);
        assertEquals(baseDao.findById(ex1.getId()), ex1);
    }

    @Test
    public void testPersist() {
        try {
            Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
            String dbURL = "jdbc:derby:memory:TestingDB;create=true";
            Connection conn = getConnection(dbURL);
            EntityManagerFactory f = Persistence.createEntityManagerFactory("TestingDB");
            EntityManager em = f.createEntityManager();
            BaseDAOImpl b = new BaseDAOImpl(Excursion.class, em);
            Calendar c = Calendar.getInstance();
            c.set(2013, 8, 24);
            Excursion ex1 = createExcursion(c.getTime(), 10, "Simple excursion 1", "New York", 35);
            ex1 = b.persist(ex1);
            assertEquals(b.findById(ex1.getId()), ex1);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(BaseDAOImplTest.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

testPersist is working and result is that this test passed. But in testPersistExcursion I get error with NullPointerException because on setUp I get:

java.lang.ClassNotFoundException: org.apache.derby.jdbc.EmbeddedDriver

I just wanted to add EntityManager as global and initialize in setUp so I don't need to write these lines again in every unit test (I saw it in some article and I think it's good aproach). But what is problem with this? Why is it working in unit test but in setUp I can't find that driver? Thanks

Edit:

I found problem and that was in maven. I have wrong artifactId. But now I have problem with "Unable to build EntityManagerFactory" at this line: emFactory = Persistence.createEntityManagerFactory("TestingDB");

My persistence unit:

<persistence-unit name="TestingDB" transaction-type="RESOURCE_LOCAL">
    <class>cz.infi.javatravelagency.entities.Reservation</class>
    <class>cz.infi.javatravelagency.entities.Trip</class>
    <class>cz.infi.javatravelagency.entities.Customer</class>
    <class>cz.infi.javatravelagency.entities.Excursion</class>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties>
      <property name="hibernate.connection.username" value="APP"/>
      <property name="hibernate.connection.driver" value="org.apache.derby.jdbc.EmbeddedDriver"/>
      <property name="hibernate.connection.password" value="APP"/>
      <property name="hibernate.connection.url" value="jdbc:derby:memory:TestingDB;create=true"/>
      <property name="hibernate.connection.autoReconnect" value="true" />  
      <property name="hibernate.connection.autoReconnectForPools" value="true" />  
      <property name="hibernate.dialect" value="org.hibernate.dialect.DerbyDialect" />  
    </properties>
  </persistence-unit>

Solution

  • Okay, further to my comment I have tried this and it works as expected. When running tests the testing specific persistence.xml in src/test/resources/META-INF is picked up as expected.

    You can then create a BaseDao class long the lines of the following:

    public class BaseDao {
    
        private static EntityManagerFactory emf;
    
        public static EntityManager getEntityManager() {
    
            if (emf == null) {
    
                emf = Persistence.createEntityManagerFactory("test");
            }
    
            return emf.createEntityManager();
        }
    }
    

    }

    Which is all a lot nicer!