简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM