Java Chatter and Random Nagging

Saturday, December 02, 2006

Lazy Unit Testing

I recently started reading
"Beyond Java" from Bruce Tate. I was sting by the following sentence in the introduction : "(..) are now stretching Java beyond its intended purpose, and that's a point. You're also increasing the barrier to entry. Ask any novice who's tried to troubleshoot a problem with Hibernate's lazy loading, or Spring's proxies.".

Today, I finally solved my unit test problems I encountered in my pet project. It had everything to do with Hibernate's lazy loading (and me being a novice in Hibernate/Spring). Since I used the Spring's Open Session In View pattern, my web application never suffered from using Hibernate's lazy collections. But during my unit tests, where I couldn't rely on this nice pattern, I encountered the following error far too many times :

org.hibernate.LazyInitializationException: failed to lazily initialize a collection

I used to fix-hack this by opening a session and lock(LOCKMODE.NONE) the asserted collection. But today I came accross this unit testing article (step 11), and I adapted my unit tests accordingly and now it works great.
The key solution was to add the following :

protected void setUp() throws Exception {
this.session = SessionFactoryUtils.
getSession(sessionFactory, true);
new SessionHolder(session));

protected void tearDown() throws Exception {
releaseSession(session, sessionFactory);

Nevertheless, Bruce definitely has a point, the development of a basic Java application has a high entry cost ! Time to check out Ruby On Rails like he suggests ?!


Post a Comment

<< Home