Posts Tagged ‘spring’
Integration Testing Queries
When you’re developing with databases, you will likely come across the need to test queries that insert, update or delete data. This usually creates a problem because the database tables quickly fill up with test data.
In one of my earlier engagements, we were using Hibernate to map a complex graph of objects. Not only did we need to test whether the usual CRUD operations worked with one object in isolation, but with entire graphs of objects. For example, deleting a customer record should delete all records from customer_orders, customer_contacts etc.
We wrote our integration tests using JUnit. To avoid cluttering the database, we used a strategy where we explicitly started a transaction in our setUp() method and rolled it back in tearDown(). The code was (somewhat) like this:
protected void setUp() throws Exception {
session = HibernateSessionFactory.newSession();
transaction = session.beginTransaction();
}
protected void tearDown() throws Exception {
session.flush();//fire all sql updates..
transaction.rollback();
HibernateSessionFactory.endSession(session);
}
In a later engagement, we came across the same problem. However, this time we were using the spring framework. The spring framework provides a class named AbstractTransactionalDataSourceSpringContextTests (Yes, the name is a mouthful). As the name suggests, this is a abstract class you can extend your (JUnit) test case from. It comes with all the usual spring auto-wiring capabilities, in addition, it automatically rolls-back the transaction at the end of each test. Regardless of the approach, integration test are a big time saver. I usually advocate integration tests for all methods invoked from a Controller (e.g.Struts Action). Having tests such as these in place makes it possible to test and debug almost all bugs right from the IDE. And thanks to the auto-rollbacks – without making a mess of test data.