我有一个在自定义验证程序中使用spring bean的约束对象:
class UserPasswordCommand {
String currentPassword
//other fields....
static constraints = {
currentPassword validator: { currPass, upc ->
Holders.applicationContext.passwordEncoder.isPasswordValid(
Holders.applicationContext.springSecurityService.currentUser.password, currPass, null)
}
}
}
但是当在单元测试中调用新的UserPasswordCommand(...)时,我得到以下信息:
java.lang.NullPointerException: Cannot get property 'currentUser' on null object
因此,似乎springSecurityService = null(按预期)。我尝试了不同的操作来模拟或“metaClass”它,但未成功。
请告知是否有更好的方法可以在命令对象中使用applicationContext中的bean,或者在Holders.applicationContext中使用某些模拟bean的方法。
提前致谢!
更新
将以下内容放入
setup()
部分:def setup() {
def appContext = Mock(ApplicationContext)
def springSecurityService = Mock(SpringSecurityService)
appContext.springSecurityService >> springSecurityService
Holders.metaClass.static.applicationContext = { appContext }
}
但是没有效果。 springSecurityService在从Holders检索到的applicationContext中为,为,为空。我究竟做错了什么?
最佳答案
您可以像这样覆盖Holder.applicationContext:
def setup() {
ApplicationContext appContext = Mock()
PasswordEncoder passwordEncoder = Mock()
passwordEncoder.isPasswordValid(_, _, _) >> true
appContext.passwordEncoder >> passwordEncoder //you can do the same for springSecurityService
//override Holder.getAplicationContext() method to return mocked context
Holders.metaClass.static.applicationContext = { appContext }
}
关于spring - ils。使用内部的Spring bean测试命令对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42887836/