Writing tests for a Grails applications is really simple. In Groovy code actually compiles when non-existing methods of objects are referenced (as opposed to Java) which makes it possible exercise TDD (test driven development).

Grails supports two types of tests out of the box, unittests and integrationtests. Tests are located in the test folder of a generated Grails project.

Lets start with a simple integration test (I'll feature webtests and the like in a follow-up to this post) for a domain object.

First, create a domain class using the "grails create-domain-class" command. This will create a domain class AND the skeleton to write integration tests for the generated class (I choose to use the Battle class of the presentation I gave yesterday). The skeleton will look something like this:

GROOVY:
  1. class BattleTests extends GroovyTestCase {
  2.     void testSomething() {
  3.     }
  4. }

Now, we want to test and see if we can store the expected fields in the battle object:

GROOVY:
  1. class BattleTests extends GroovyTestCase {
  2.     void testCRUD() {
  3.         Battle b = new Battle(name: "BOTG 2007", description: "Finalists' BOTG 2007", date: new Date())
  4.         b.save();
  5.        
  6.         assert Battle.get(b.id) != null
  7.         assert b.name == "BOTG 2007"
  8.     }
  9. }

Running the test (grails test-app Battle) results, as expected in a failure:

CODE:
  1. Running 1 Integration Test...
  2. Running test BattleTests...
  3.                     testCRUD...FAILURE

After running the tests Grails creates a nice HTML overview of all the results as well:

Test report

In the image above you'll see the error message "No such property: name for class: Battle
". Adding the property to the Battle class fixes this and results in a successful test:

CODE:
  1. Running 1 Integration Test...
  2. Running test BattleTests...
  3.                     testCRUD...SUCCESS

Apart from the default assertion methods inherited from the JUnit framework's TestCase class, GroovyTestCase also offers a couple of other assertions handing us quite a useful/complete set of tools.


2 Responses to “Grails and tests - Part I: Getting started with TDD”

  1. 1 Grails and tests - Part II: Testing dynamic taglibs using XmlSlurper at log4p
  2. 2 Behavior Driven Development at log4p

Leave a Reply





About

Welcome to the weblog of Peter Maas. Here you'll find various posts related to stuff I like (like my kids and espresso) and stuff I do (like developing software).

JavaOne 2008 Pictures

lan_vpro train IMG_6149 IMG_4609.JPG Stretched Limo IMG_4572 Charles Nutter on JRuby raadhuis_hilversum trap trap (II) Greenland pier_39 warm_en_koud edwinmartin breakfast oldtimer IMG_4567 italian_chef IMG_4636.JPG Joshua Bloch at JavaOne2008
View more photos >

Categories



Meld u aan voor PayPal en begin direct met het accepteren van creditcardbetalingen.