I having a method in command class
, which use messageSource.getMessage(...)
, as messageSource won't get injected into the commandClass
. I use
def messageSource = Holders.applicationContext.getBean("messageSource")
inside the commandClass
.
My problem is when trying to write unit test
this method,
@Before
void setup() {
Holders.applicationContext.getBean("messageSource")
}
void "testFunction"() {
//inside testFunction I am using messageSource
given:
//required things
when:
//call the function
then:
//assert
}
after testing this function, I getting the error
java.lang.IllegalArgumentException: ServletContext must not be null
at grails.util.Holders.getApplicationContext(Holders.java:80)
Can someone suggest on how to resolve this one.
Update
@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
}
}
}
Thanks in Advance
I found the answer
void setup() {
mockApplicationContext()
}
def static mockApplicationContext() {
GrailsUnitTestMixin.initGrailsApplication()
Holders.grailsApplication = GrailsUnitTestMixin.grailsApplication
Holders.metaClass.'static'.getApplicationContext = { ->
return GrailsUnitTestMixin.applicationContext
}
Holders.metaClass.applicationContext.getBean = { bean ->
return GrailsUnitTestMixin.messageSource
}
}
I 'll update more about the answer later
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With