Tuesday, December 1, 2009

Grails Goodness: Mocking the Configuration in Unit Tests

When we write a unit test for our Grails service and in the service we use ConfigurationHolder.config to get the Grails configuration we get null for the config object when we run the unit test. Which is fine for a unit test, because we want to provide values for the configuration in our test. This is easy to do: we use the mockConfig method to set configuration values for the unit test. The method accepts a String that is a configuration script.

// File: grails-app/services/SimpleService.groovy
import org.codehaus.groovy.grails.common.ConfigurationHolder as GrailsConfig

class SimpleService {
    String say(text) {
        "$GrailsConfig.config.simple.greeting $text"
    String sayConfig() {
// File: test/unit/SimpleServiceTests.groovy
import grails.test.*

class SimpleServiceTests extends GrailsUnitTestCase {
    def service
    protected void setUp() {
        service = new SimpleService()
            simple {
                greeting = 'Hello'
                text = 'world.'
    protected void tearDown() {
        service = null
    void testSayConfig() {
        assertEquals 'Hello world.', service.sayConfig()
    void testSay() {
        assertEquals 'Hello mrhaki', service.say('mrhaki')


Derek said...

Thank you!! Was having trouble with null config values in service integration tests

Tomas Lin said...

Often, when you have a plugin with a bunch of config values, it is useful to use the file directly.

mockConfig( new File( 'grails-app/conf/NimbleConfig.groovy' ).text + '''mynewAwesomeval = 9''')

mrhaki said...

@Tomas Lin: Thank you for your comment. Very useful piece of code and saves a lot of typing.

Anonymous said...

Thanks for this example. It was very timely for my tagLib testing.

rsilva said...

what's the best way to do the setUp in grails 2.0.0? Using @Before annotation?

Thank you

Post a Comment