Useful Grails Integration Testing Snippet: Delete All Instances of Domain Classes

Just thought I’d share this quick:

import org.codehaus.groovy.grails.commons.ApplicationHolder
 
class FooTests extends GroovyTestCase {
 
  def sessionFactory
 
  void setUp() {
    (ApplicationHolder.application.getArtefacts("Domain") as List).each {
      it.newInstance().list()*.delete()
    }
    sessionFactory.currentSession.flush()
    sessionFactory.currentSession.clear()
  }
}

That code deletes all the instances of all the domain classes. Yes, the transactional aspect of Grails integration tests should make sure everything is rolled back properly. But there’s always something that sneaks into the database one way or another (often as the result of exception handling or other weirdness), so I like to be thorough. I had the same problem back when I was developing Rails. If you have that problem, feel free to have at the above code.

Also note the usefulness of Spring dependency injection here, despite using a dynamic language. It has been asserted that “real” dynamic languages don’t need Spring, but I find that assertion really, really odd.

This entry was posted in To Be Categorized. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

2 Comments

  1. Taras Matyashovsky
    Posted February 5, 2009 at 4:56 PM | Permalink

    Thanks, was very useful for me.

  2. Posted October 15, 2009 at 1:11 AM | Permalink

    Thanks a ton!!

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">