views:

170

answers:

2

I am trying to implement JUnit tests for a class that performs DB queries using Hibernate. When I create the class under test, I get access to the session through the factory by doing the following:

InitialContext context = new InitialContext();
sessionFactory = (SessionFactory) context.lookup(hibernateContext);

This works fine when I deploy this to JBoss 5.1. I am trying to figure out how to get this to work with my JUnit test. I keep getting an exception stating that I "Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial". I've searched high and low but haven't been able to find any information about what specifically I need to do to get this to work. I am not using Spring or any frameworks, just plain old Java and JUnit.

+2  A: 

In a unit test context, you very likely don't want to get your session factory from JNDI (you don't want to start JBoss for unit tests) and my recommendation would be to use a good old HibernateUtil helper class. Below, a very basic example:

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new Configuration().configure().buildSessionFactory();
        }
        catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

}

Just in case, the caveat emptor sample application (the native version) has a a more advanced version that can get a global SessionFactory either from a static variable or a JNDI lookup (so you can use the same code in and outside the container).

Personally, I've used the one from Cameron McKenzie during a long time.

Then, get a Session from the SessionFactory and begin/commit/rollback a transaction for each method in your unit test.

Pascal Thivent