Loading...

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() {
        say(GrailsConfig.config.simple.text)
    }
}
// File: test/unit/SimpleServiceTests.groovy
import grails.test.*

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