如何在Grails的Config.groovy中模拟单元测试的值

B K*_*B K 1 grails groovy unit-testing mocking

我想写一些测试用例,我必须模拟配置文件的一些属性.

下面显示的是实际代码

if (password.length() < grailsApplication.config.user.password.min.length) {
    return false
}
Run Code Online (Sandbox Code Playgroud)

我想模拟grailsApplication.config.user.password.min.length 在我的配置文件中,user.password.min.length已设置为6

我试着用以下方式嘲笑:

  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)

但这一切都没有效果.我的代码NullPointerException有时会抛出.有人可以建议正确的方法来模拟配置文件吗?

meh*_*ood 6

以下是我在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"]
}
Run Code Online (Sandbox Code Playgroud)

注意:my.prop我正在使用内部getSomething(string)方法的属性.