Monday, May 11, 2009

Testing Standalone GORM

Setting up GORM(Groovy ORM) in a web app without grails is not a terribly hard task to do and is well documented. However, figuring out how to write unit test for your GORM classes was a bit more challenging. Now, I am not saying this is the end all, be all way of doing this and I am sure there are other ways, but this is what I came up with in my research. Feel free to comment if there is a better way. The approach going into this was that GORM is hibernate under the hood. So in order to write a test for this we just need to setup our test as if it was hibernate. This seemed like a good way to start, so here goes.

class MyGormTest extends AbstractTransactionalDataSourceSpringContextTests {

  SessionFactory sessionFactory
  
  /**
   * Turn off dependency injection.
   */ 
  def MyGormTest() {
      super.setDependencyCheck(false)
  }
  
  /**
   * Load the spring configuration files.
   */
  @Override
  protected String[] getConfigLocations() {
      return ["applicationContext.xml"]
  }
  
  /**
   * Manually set the sessionFactory.
   */
  @Override
  protected void onSetUp() throws Exception {
      this.sessionFactory = (SessionFactory)
      super.getApplicationContext().getBean("sessionFactory")    
  }

  /**
   * Write your test.
   */
  void testSave() {
      assertEquals(0, User.count())
      User user = new User(name: 'Test User').save(flush:true)
      assertEquals(1, User.count())
      user.delete(flush: true)
      assertEquals(0, User.count())
  }
}

A few things to go over here:
  1. Since GORM is hibernate under the hood, we need our test to extend AbstractTransactionalDataSourceSpringContextTests
  2. All your test will need to turn off the dependency checking. We do this in the constuctor of the test with, super.setDependencyCheck(false). This is done as a work around from getting an Unsatisfied Dependency 'metaClass' error when using groovy classes in the ApplicationContext. View this thread for more details.
  3. Now, because we are turning off the dependency check we will need to manually set the session factory, we do this before we run each test in the onSetUp() method.
  4. Obviously in order to manually set the sessionFactory we need to get the sessionFactory bean from the config files. These config files are loaded using the getConfigLocations() method. Once they are loaded you can obtain the bean from the ApplicationContext.

No comments:

Post a Comment