Testing Grails services with easyb

Posted by: Andrew Glover on 2010-10-28 15:32:00.0

The Grails easyb plugin has a nifty feature for obtaining instances of service classes. Simply call inject along with the name of your service (i.e. “dateService”) and it’ll auto-magically be available as a variable.

Before you can use this feature, you first must install the easyb plugin like so:

%>grails install-plugin easyb

You can place your .story files (or .specification ones) in any of the sub-directories found in the test directory. For example, if I have a service dubbed DateFormatService that I wish to verify in an easyb story, I can create a story dubbed DateProcessing.story in my test/integration directory.

The story is simple:

scenario "string dates should be converted correctly", {
  given "a date service object", {
    inject "dateFormatService"
  }

  and "and date string", {
    param = "10/07/2010"
  }

  then "the service should return date objects in various formats", {
    date = dateFormatService.day01(param)
    date.time.shouldBe 1285905600000 //i.e. 10/01/2010

    date2 = dateFormatService.day28(param)
    date2.time.shouldBe 1288238400000 //i.e. 10/28/2010
  }
}

Note, to validate java.util.Date instances, I simply convert them into longs and ensure the epoch time is correct. And as you can see from the code above, the call to inject "dateFormatService" makes a variable dubbed dateFormatService available.

By calling inject the entire dependency graph is formally injected too — that is, if service class Foo has a reference to service Bar, then when Foo is injected into an easyb story, Bar will have been pre-injected into Foo (which is distinctly different than calling new Bar().

Invoking the story from the command line is easy too:

%>grails test-app :easyb

This command runs any easyb file found — you can also run individual stories and directories of stories.

For more information on the easyb Grails plugin, check out the Grails plugin page — if you have questions, join the easyb mailing list, baby!

Looking to spin up Continuous Integration quickly? Check out www.ciinabox.com.


be the first to rate this blog

About Andrew Glover

Andrew Glover

Andrew is the founder of the easyb BDD framework and the co-author of Addison Wesley's "Continuous Integration", Manning's "Groovy in Action" and "Java Testing Patterns". He is an author for multiple online publications including IBM's developerWorks and Oreilly's ONJava and ONLamp portals. He actively blogs about software at thediscoblog.com.

More About Andrew »

NFJS, the Magazine

2010-10-01 00:00:00.0 Issue Now Available
  • What's Brewing in Java 7: The Language Features
    by Venkat Subramaniam
  • Waste!
    by Hamlet D`Arcy
  • Arquillian: A component Model for Integration Testing
    by Dan Allen
  • Spring Roo - A Jump-Start for Your Java Project
    by Paul Chapman
Learn More »