Wednesday, August 9, 2006

JUnit Tests for Spring and Hibernate

There are two big things that I love about the Spring Framework:

  1. It has excellent Hibernate support through the use of its HibernateTemplate class
  2. It makes writing JUnit tests much simpler, yielding better code
However, up until now I hadn't been able to find a good way to combine these two beneftis and JUnit test Hibernate-based code that I had written using Spring as my foundataion. (Mostly because I'd never really bothered putting any effort into figuring out the best way to do it) Up until now, I had my JUnit tests create a Spring ApplicationContext, and simply obtained my Hibernate DAO and ran my tests. While this did accomplish my goal of determining if my Hibernate-based code was working properly, it was poor design, and was terribly inefficient.

Recently, however, I came across a great article explaining how to unit test Hibernate mapping configurations. The article goes into how to create your session factory, and wire up your DAO with a new HibernateTemplate. It even gives tips on how to setup an in-memory HSQLDB database for testing. This reduces the overhead needed to perform your tests, as you don't need a full-fledged SQL database to run your tests against.

If you write any Hibernate-based code and are looking for a means of testing your Hibernate configuration, this is article is a great referrence.