Fork me on GitHub

21 Apr 2010

A Grails JUnit 4 test template

Grails 1.3 upgrades the bundles JUnit to the newer JUnit 4 API. However, the test template used to generate classes by the Grails create-* scripts is still very JUnit 3-ish. Here's a replacement that will generate a skeleton test using JUnit 4 conventions:

@artifact.package@import grails.test.*
import org.junit.*
import static org.junit.Assert.*
import static org.hamcrest.CoreMatchers.*
import static org.junit.matchers.JUnitMatchers.*

class @artifact.name@ {
    @Before void setUp() {
    }

    @After void tearDown() {
    }

    @Test void something() {

    }
}

To use this just run grails install-templates then copy the contents over the file src/templates/artifacts/Tests.groovy. You can delete anything else in the src/templates directory that you don't need. Then every time you use a Grails command such as grails create-service foo the generated test will use the JUnit 4 template.

3 comments:

Ted Naleid said...

I like this better, you should submit this as a patch to grails.

Richard Paul said...

I'm also a fan of JUnit4, but when you start using mockDomain for unit testing with Grails entities you start to run into problems.

e.g. calling MockUtils.mockDomain manually will permanently change the metaclass of your entity, thus causing leaking behaviour between tests.

The JUnit3 style tear down automatically resets the meta class for all entities that had mockDomain called on them.

Rob said...

With a JUnit 4 test you can still extend GrailsUnitTestCase and call super.tearDown