Mocking configuration in Grails for unit testing

Configuration can be a bit hairy to test in grails unit tests. While there is an official technique that I found in a JIRA that looks like this:

mockConfig '''
john.doe.name = "bill"
'''

I’ve never gotten it to work. I’ve fallen back to using the Groovy provided meta-programming techniques. This means you need to mock the configuration differently depending on how you access your configuration.

No matter what, start by creating a ConfigObject()

def mockedConfig = new ConfigObject()
mockedConfig.john.doe.name = "bill"

The next step depends on how you’re accessing config in the code you’re testing. If you’re using ConfiguratoinHolder, try this

ConfigurationHolder.config = mockedConfig

On the other hand, if you’re using grailsApplication, this will work better.

GrailsApplication.metaClass.getConfig = {-> mockedConfig }

This is yet another reason to be consistent in your coding. If you’re not consistent you may end up mocking both.