我在command class中有一个使用messageSource.getMessage(...)的方法,因为messageSource不会注入(inject)到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 nullat 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
        }

    }
}

提前致谢

最佳答案

我找到了答案

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
    }
}

稍后我将更新有关答案的更多信息

10-07 16:30