Lazy Unit Testing
<preamble>
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 good...to 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.".
</preamble>
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);
TransactionSynchronizationManager.
bindResource(sessionFactory,
new SessionHolder(session));
}
protected void tearDown() throws Exception {
TransactionSynchronizationManager.
unbindResource(sessionFactory);
SessionFactoryUtils.
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 ?!
0 Comments:
Post a Comment
<< Home