Wednesday, December 13, 2006

Faster DAO testing

If you're prepared to step away just a little bit from how the production environment is set up, here's one way to speed up Hibernate DAO testing considerably:

First of all, don't add a (Annotation)LocalSessionFactoryBean to your test context, just a DataSource and a hibernate.cfg.xml, and don't add any mapped/annotated classes to the configuration file either. Then create a base DAO test class that looks something like this:

public class AbstractDaoTest {

SessionFactory sessionFactory;

public AbstractDaoTest(Class... classes)
{
// Read hibernate.cfg.xml from root of classpath, for example src/test/resources
Configuration configuration = new Configuration();
for (Class clazz : classes) {
configuration.addClass(clazz);
}
sessionFactory = configuration.buildSessionFactory();
}

}

Then place all your DAOs and the DataSource in the test application context, and start writing your DAO tests like this:

public class ParentDaoTest extends AbstractDaoTest {

ParentDao dao;

public ParentDaoTest() {
// Parent has a relation to the Child class, so we need two classes mapped
super(Parent.class, Child.class);
}

public void setParentDao(ParentDao dao)
this.dao = dao;
}

public void testSomething() {
// Stuff that involves Parent and Child
}

}

Now there's only two classes that Hibernate needs to parse metadata for and create CRUD SQL for and so on, which can speed up application context startup considerably compared to mapping all domain classes, if you have 10-20 classes in you domain model.

No comments: