Attempting a Unit Test of a class that makes DB queries with Hibernate and cannot create a session
I am trying to implement JUnit tests for a class that does DB queries using Hibernate. When I create the class under test, I access the session through the factory by doing the following:
InitialContext context = new InitialContext(); sessionFactory = (SessionFactory) context.lookup(hibernateContext);
This works great 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 the class name in the environment or system property or as an applet parameter or in the application resource file: java.naming.factory.initial". I searched high and low but couldn't find any information on what exactly I need to do to get this to work. I am not using Spring or any frameworks, just old Java and JUnit.
a source to share
In the context of a unit test, you most likely don't want to get a factory session from JNDI (you don't want to run JBoss for unit tests), and my recommendation would be to use the old old HibernateUtil
helper class . Below is a very simple 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 app (native version) has a more advanced version that can get the global SessionFactory from either a static variable or JNDI lookup (so you can use the same code inside and outside the container).
Personally, I've been using the one from Cameron McKenzie for a long time.
Then get Session
from SessionFactory
and start / end / rollback the transaction for each method in the unit test.
a source to share