Search code examples
unit-testinggrailsgroovymocking

How to mock values in Config.groovy in Grails for unit testing


I want to write some test cases where I have to mock some properties of the config file.

Below shown is the actual code

if (password.length() < grailsApplication.config.user.password.min.length) {
    return false
}

I want to mock grailsApplication.config.user.password.min.length In my config file, user.password.min.length has been set as 6

I tried to mock in the following ways:

  1. mockConfig = new ConfigObject()
    mockConfig.user.password.min.length = 6

  2. mockConfig("user.password.min.length")

  3. mockConfig(user.password.min.length)
  4. mockConfig(mockConfig.user.password.min.length)

But none of this is working. My code is throwing NullPointerException sometimes. Could someone please advise the correct way to mock the config file?


Solution

  • Following is how I mock my config properties in Service spec.

    @TestFor(MyService)
    class MyServiceSpec extends Specification {
    
    void "Test case for somemethod" () {
        given:
        grailsApplication.config.my.prop= 'some-prop-value'
    
        when:
        def result = service.getSomething(keyword)
    
        then:
        result.label.every {
            it.toLowerCase().contains(keyword)
        }
    
        where:
        keyword << ["dub", "sing"]
    }
    

    Note: my.prop is the property I'm using inside getSomething(string) method.