Friday, December 05, 2008

OSIV-like Behaviour for Unit Tests

It is fairly common when writing unit tests to use mock objects in place of DAOs, and the whole issue of lazy loading is avoided, since the mock objects will simply be created to satisfy whatever conditions are required for testing to work. In some cases, however, such as with functional or acceptance testing, it is sometimes desirable to hit an actual test database. This seems simple enough until you realize that Spring's Open Session in View (or Open Entity Manager in View) has been handling sessions for you so that traversing lazy relationships work. Without it, you get a session long enough to execute a 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);
}

Labels: ,


Comments: Post a Comment





<< Home

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]