Grails 文档指出:
在集成测试期间调用操作时,Grails 不会调用拦截器或 servlet 过滤器。您应该单独测试拦截器和过滤器,必要时使用功能测试。
这也适用于单元测试,您的控制器操作不受定义的拦截器的影响。
鉴于您有:
def afterInterceptor = [action: this.&interceptAfter, only: ['actionWithAfterInterceptor','someOther']]
private interceptAfter(model) { model.lastName = "Threepwood" }
要测试拦截器,您应该:
验证拦截是否应用于所需的操作
void "After interceptor applied to correct actions"() {
expect: 'Interceptor method is the correct one'
controller.afterInterceptor.action.method == "interceptAfter"
and: 'Interceptor is applied to correct action'
that controller.afterInterceptor.only, contains('actionWithAfterInterceptor','someOther')
}
验证拦截器方法是否达到预期效果
void "Verify interceptor functionality"() {
when: 'After interceptor is applied to the model'
def model = [firstName: "Guybrush"]
controller.afterInterceptor.action.doCall(model)
then: 'Model is modified as expected'
model.firstName == "Guybrush"
model.lastName == "Threepwood"
}
或者,如果您没有拦截器,请确认没有拦截器
void "Verify there is no before interceptor"() {
expect: 'There is no before interceptor'
!controller.hasProperty('beforeInterceptor')
}
这些示例用于在拦截器之后进行测试,但同样适用于拦截器之前。