【发布时间】:2014-10-23 09:40:01
【问题描述】:
我在command class 中有一个方法,它使用messageSource.getMessage(...),因为messageSource 不会被注入commandClass。我用
def messageSource = Holders.applicationContext.getBean("messageSource") 在commandClass 内。
我的问题是在尝试写unit test这个方法时,
@Before
void setup() {
Holders.applicationContext.getBean("messageSource")
}
void "testFunction"() {
//inside testFunction I am using messageSource
given:
//required things
when:
//call the function
then:
//assert
}
测试此功能后,我得到了错误
java.lang.IllegalArgumentException: ServletContext must not be null
at grails.util.Holders.getApplicationContext(Holders.java:80)
有人可以建议如何解决这个问题。
更新
@Validateable
class commandClass {
//required fields and constraints
def formatData(List<commandClass> commandObjs) {
StringBuilder validationErrors
commandObjs.each {commandObj->
validationErrors = new StringBuilder()
if(commandObj.hasErrors()) {
commandObj.errors.allErrors.each {it ->
validationErrors.append(messageSource.getMessage(it, null)).append('\n')
}
}
commandObj.metaClass.validationErrors = validationErrors
}
}
}
提前致谢
【问题讨论】:
-
请提供问题中的Command类?