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

someService:
  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.

@TestFor(MyService)
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.