grails spock测试失败'java.lang.IllegalArgumentException:ServletContext不能为null'

Sug*_*lai 6 java grails spock

我有一个方法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
}
Run Code Online (Sandbox Code Playgroud)

在测试此功能后,我收到错误

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
        }

    }
} 
Run Code Online (Sandbox Code Playgroud)

提前致谢

Sug*_*lai 5

我找到了答案

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
    }
}
Run Code Online (Sandbox Code Playgroud)

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