Thursday 28 November 2013

Testing a command object without a controller

Sometimes you just want to test a command object in a Spock specification without having to use @TestFor with an existing controller class passed as an argument.

Back in time (last week or so XD ) I used to do it this way

import spock.lang.Specification
import grails.test.mixin.TestFor

@TestFor(SomeControllerClass)
class MyCommandObjectSpec extends Specification {
   // ... your stuff
}

But the thing is that Grails wraps all its mocking functionality in "mixins"  and the way you can apply those mixins is through the @TestMixin annotation.

Normally you don't notice this behavior because the annotation @TestFor does that under the hood, but if you had to apply controller mocking behavior in your specification you should be using the @TestMixin annotation with the ControllerUnitTestMixin directly:

import spock.lang.Specification
import grails.test.mixin.TestMixin
import grails.test.mixin.web.ControllerUnitTestMixin

@TestMixin(ControllerUnitTestMixin)
class MyCommandObjectSpec extends Specification {
  //... your stuff
}

Happy testing :)

1 comment:

  1. We provides focus and result-oriented training session, which equipped you with skill development
    to getting best career option in the industries. We offer basic to advance level

    for more information please visit:

    Oracle Fusion HCM Training

    ReplyDelete