Spock with Grails

In this post, i hope to cover installing, configuring and using Spock testing framework with Grails. Spock is a testing and specification framework for Java and Groovy applications.

Environment at the writing: jdk1.7.0_07, Grails 2.1.1

1. Installing & Configuring Spock Plugin

One Way – Configure Spock by adding following line in \grails-app\conf\BuildConfig.groovy:

At compile time, Grails will detect that you have configured Spock and install the plugin

Second Way – Run command ‘grails install-plugin spock’ from command line and it will install&configure the Spock for you

To verify at any time, open the dependency report by calling command ‘grails dependency-report” or ‘open dep-report’ from interactive grails console. The report will look like the following:

From the report, look at theĀ  ‘test’ tab to see the ‘Spock’ Plugin

2. Implementing

For Unit Tests – extend your Test class with ‘UnitSpec’ and import the library as following:

For Integration Tests – extend your Test class with ‘IntegrationSpec’ and import the library as following:

4. Running Tests

To Run Unit Tests – one way is to call command ‘grails test-app unit:spock <nameOfTestClass>.<nameOfTest>’ . The other way is depending on your IDEĀ  (IntellJ right click from test itself->Run)

To Run Integration Tests – one way is to call command ‘grails test-app integration:spock <nameOfTestClass>.<nameOfTest>’. The other way is depending on your IDE (IntellJ right click from test itself ->Run)

5. Other

Sharing or Reusing – Spock allows an easy way to reuse or share an object among the individual tests(method features) as following:

Its accomplished by adding notation ‘@Shared’ when declaring the object. Also, don’t forget to import ‘spock.lang.Shared’ package

Sources:

 

Issues Encountered:

1. “Cannot get property ‘autowireCapableBeanFactory’ on null object”. We were getting these because for Integration test we cannot use Unit test mixines, so by dropping @TestFor(class) and @TestMixin(GrailsUnitTestMixin) it solved the problem

Leave a Reply

Your email address will not be published. Required fields are marked *