Grails 3.3 Integration Testing with Spock Mocks

It is easy to use the Spock Framework, shipped with Grails, to mock or stub a collaborator (such as a service) in our Grails unit tests.

The Testing chapter explains a bit about mocking collaborators, doWithSpring/doWithConfig callback methods, the FreshRuntime annotation to mock beans in tests — but they’re mainly for unit testing.

How about mocking beans in an integration test?

Continue reading “Grails 3.3 Integration Testing with Spock Mocks”

How to mock configuration in a Grails unit- or integration test?

Sometimes you may need to mock Grails (application) configuration in an unit or integration test.

E.g. you want to test code which normally would access the property jmxEnabled from the following configuration block:

In Grails 2 in Config.groovy

someService {
  jmxEnabled = true

or Grails 3 in application.yml

  jmxEnabled: true

Here’s are the most simple options for a Grails 2.4.x or Grails 3.0.x Spock unit- or integration test.

Unit test

In your unit test you have an implicit config reference you can use. Either in a specific test or in a setup() initialize it with a value you want to test with.

class MyServiceSpec extends Specification {

  def setup() {
    config.someService.jmxEnabled = false

This is actually the getConfig() method in the GrailsUnitTestMixin class which Grails automatically “mixes” into your unit test class.

Integration test

In your integration test, inject grailsApplication as a bean and access the configuration through its config property – just as you would in the actual production code.

class MyServiceIntegrationSpec extends Specification {

  def grailsApplication

  def setup() {
    grailsApplication.config.someService.jmxEnabled = false

Written for Grails 2.4+ and Grails 3.0.x.