Grails

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

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.

4 comments

  1. The part about integration test shows how to access, but not how to stub calls to config and their return values. The easiest way would be just to change the config value (or a branch of config values) to the desired one (or to your own ConfigObject), but then you would have to ensure that the original value is restored at the test cleanup. With a controller integration test, you could clone the config (or its relevant part) and attach to the instance of the controller under test.

    Like

    1. Hi Yaroslav, you’re right – may be I can make some examples soon of what you’re suggesting. Thank you for your feedback.

      Like

Comments are closed.