我想写一些测试用例,我必须模拟配置文件的一些属性。
下面显示的是实际代码
if (password.length() < grailsApplication.config.user.password.min.length) {
return false
}
我想模仿grailsApplication.config.user.password.min.length
在我的配置文件中,user.password.min.length
已设置为6
我试着用以下方式嘲笑:
mockConfig = new ConfigObject()
mockConfig.user.password.min.length = 6
mockConfig("user.password.min.length")
mockConfig(user.password.min.length)
mockConfig(mockConfig.user.password.min.length)
但这一切都没有效果。我的代码有时会抛出NullPointerException
。
有人可以建议模拟配置文件的正确方法吗?
答案 0 :(得分:6)
以下是我在服务规范中模拟配置属性的方法。
@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"]
}
注意:my.prop
是我在getSomething(string)
方法中使用的属性。