Spring/Hibernate unit testing

Spring provides some nice tools to assist in unit testing with Hibernate, which are well covered in Spring’s excellent documentation. I want to recap some basics here, though. Later on I want to talk about persistence layer test generation, and I’ll need to refer back to these notes.

One of Spring’s convenient tools is a base test class that does a number of nifty things:

  • Sets up your application context, including Hibernate SessionFactory if you have one.
  • Uses that context to do DI into your test classes, which is a nice way to access your singletons within your tests.
  • Wraps each test method in a transaction which gets rolled back at the end of the method. Complete test isolation with zero work on your part!

In use, it looks something like this:

// This tells spring where to find my config.  Note that this could be a special test config rather than my production config
@ContextConfiguration(locations={"/myApplicationContext.xml"})
public class MyContextTests extends  AbstractTransactionalJUnit4SpringContextTests   {
	
        // Standard Spring DI
	@Resource protected SessionFactory sf;
	
       // a basic unit test (utility methods omitted).  Note that I'm creating new objects and flushing them to the database,
       // but not bothering to clean up in any way.
	@Test
	public void testCategoryManager_createDuplicateInDifferentService() {		
		Category category = createCategory("PCTEST");
		assertEquals("PCTEST", category.getName());
		sf.getCurrentSession().flush();	
		createCategoryFromOtherService("PCTEST");
	}	
}

This is a godsend for most test scenarios. It falls down in some ways, though, and I’ll talk about that in my next post.

Leave a Reply

Your email address will not be published. Required fields are marked *