You need to simulate the OpenSessionInViewInterceptor behaviour in your Unit Tests.
I use the following class for Spring/Hibernate/JUnit tests
Code:
//Hibernate imports
import net.sf.hibernate.FlushMode;
import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;
//Spring imports
import org.springframework.orm.hibernate.SessionFactoryUtils;
import org.springframework.orm.hibernate.SessionHolder;
import org.springframework.transaction.support.TransactionSynchronizationManager;
//Taha imports
import org.taha.spring.BaseSpringTest;
/**
* @author <a href="mailto:irbouh@videotron.ca">Omar Irbouh</a>
* @version 0.1
* @since 2004.03.03
*/
public abstract class BaseSpringHibernateTest extends BaseSpringTest {
protected static final String SESSION_FACTORY = "sessionFactory";
protected SessionFactory sessionFactory = null;
protected void setUp() throws Exception {
super.setUp();
sessionFactory = (SessionFactory) getApplicationContext().getBean(SESSION_FACTORY);
Session session = SessionFactoryUtils.getSession(sessionFactory, true);
session.setFlushMode(FlushMode.NEVER);
TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
}
protected void tearDown() throws Exception {
SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory);
SessionFactoryUtils.closeSessionIfNecessary(sessionHolder.getSession(), sessionFactory);
super.tearDown();
}
}
org.taha.spring.BaseSpringTest is a simillar abstract class responsible for building the ApplicatinContext. You can remove the dependance on BaseSpringTest and add a method getApplicationContext() that returns the ApplicationContext.
HTH.