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:

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

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