martes, 12 de abril de 2011

Mocking config parameters

A few days ago, I was writing my testing class for a controller, and i found that I didn't know how to mock a config parameter from Config.groovy.

Supose the following example:

You need to obtain the facebook url from the Config.groovy

environments {
    production {
        grails.facebookURL = "http://www.facebook.url"
    }
}


You have a controller groovy class:

// URLController.groovy
public class UrlController{
    public String getFacebookUrl(){
        return ConfigurationHolder.config.grails.facebookURL;
    }
}


And you want to build its respective unit test:

// URLControllerTests.groovy
public class UrlControllerTests extends GrailsUnitTestCase{
     def urlController;
     public void setUp(){
          super.setUp();
          urlController = new UrlController();
    }
     public void test_getFacebookURL(){
        //Mock configurationholder like this
        ConfigurationHolder.config = [ grails: [facebookURL: 'http://www.facebook.com'] ];
        assertEquals("http://www.facebook.com",urlController.getFacebookUrl());
    }
}


Voila!

1 comentario: