Testing with Grails

The Grails testing framework enables you to define a series of tests, both at the Unit and Integration level, to run the suite with results reporting, and to supply test data.  This page describes how to integrate Automated Business Logic into the Grails testing framework under STS (Spring Source Tool Suite).


Just as you must configure Grails to engage business logic when running applications, you must also engage it when running tests.  You do so using the same approach, shown below:

Bootstrap for test data

Grails provides a very helpful mechanism for creating test data, refreshed for each run.  Such data is created using normal Gorm API's as shown below.  Since business logic hooks into Gorm/Hibernate events, this data is subjected to your rules so will conform to your constraint and derivation rules.  This relieves you of a great deal of tedium in creating correct test data, or debugging logic based on bad existing data.

Test Development

Create tests for your domain objects as Integration tests, so you have full access to the framework, test data bootstrapping, and so forth.  Salient points regarding the test shown below:
  1. Integration tests are, be default, rolled back.  This interferes with business logic, which occurs on commit. It is therefore critical you include the first line shown to set transactional false

  2. Along the same lines, observe that the actual test is performed inside a withTransaction block


Successful tests must not only run without stacktraces, they must produce the correct result.  The last line shown in the screenshot above utilizes a SnapShotDB utility that
  • captures the initial database state (line 36)

  • captures the final database state, and provides a change log upon which you can assert expected changes (last line)
SnapShotDB works by maintaining a full database copy in memory, so be aware of the implications described in the link.  This is clearly appropriate only for very small databases.

To determine what to code into the snapShot.assertChanged(<a string>), run the test with breakpoint at line 54, and examine what was changed, and which changes you need to verify:

Grails Report

Grails produces a report like this, accessed via the hyperlink in the console:


There is still a benign stacktrace run the Integration test in the TestApp.class:

javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial