Tuesday, September 20, 2005

Unit testing DAO classes in the Spring Framework

One of the major claims of the Spring framework is its non-intrusiveness, which, among other things, permits to unit test all classes managed by the Spring container.

So, it is natural that I felt very surprised when yesterday my unit test failed two times while testing a DAO class, based on Hibernate and implemented with the HibernateDaoSupport class provided by Spring.

The first time, my unit test failed because I instantiated my DAO object directly through the no-arg constructor: no one set the Hibernate SessionFactory (normally injected by the Spring container), so this was the problem.
I solved the problem creating a SessionFactory into my unit test, and setting it into the DAO object, as I were the Spring container.

Big surprise, the unit test failed a second time, screaming for no TransactionManager found ... but there was no method for setting such a thing in the DAO object!

So, is the unit testability of Spring managed objects only valid for THAT objects NOT using DAO templates?

The answer is no, you can unit test also them.
In the case of Hibernate, simply create and set by yourself a SessionFactory, like said before, and avoid using Session objects directly into your DAO code.
Just use the template facilities, like the getHibernateTemplate().find(...) methods, or, if you must directly use Query or Criteria APIs, encapsulate the access to the Session in the HibernateCallback class provided by Spring, which automatically manages the session and its transactions.

More and more powerful, more and more lightweight.

No comments: