Friday, December 05, 2008
OSIV-like Behaviour for Unit Tests
dao.find()
and then the first time you attempt to traverse a lazy relationship, you get an exception.Fortunately, with jUnit, it is fairly easy to create a
setUp
and tearDown
to behave similarly to the start and end of a servlet request, and Spring provides the means to associate a session with the current thread, making things work basically the same way as they do with OSIV. Just do something like this:@Before
public void setUp()
{
Session session = SessionFactoryUtils.getSession(sessionFactory, true);
TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
}
@After
public void tearDown()
{
SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory);
SessionFactoryUtils.releaseSession(sessionHolder.getSession(), sessionFactory);
}
Subscribe to Posts [Atom]