0

我有一个拦截器,它在模型对象上设置一个属性。在单元测试中,模型为空。

拦截器

import groovy.transform.CompileStatic
import groovy.util.logging.Commons

@CompileStatic
@Commons
class FooInterceptor {

    FooInterceptor() {
        matchAll()
    }

    boolean after() {
        model.foo = 'bar'
        true
    }
}

规格

import grails.test.mixin.TestFor
import spock.lang.Specification

@TestFor(FooInterceptor)
class FooInterceptorSpec extends Specification {
    void "Test Foo interceptor loads var to model"() {
        when: "A request matches the interceptor"
            withRequest(controller: 'foo', action: 'index')
            interceptor.after()

        then: "The interceptor loads the model"
            interceptor.doesMatch()
            interceptor.model.foo == 'bar'
    }
}

堆栈跟踪

Cannot set property 'foo' on null object
java.lang.NullPointerException: Cannot set property 'foo' on null object
    at bsb.core.web.FooInterceptor.after(FooInterceptor.groovy:13)
    at bsb.core.web.FooInterceptorSpec.Test Foo interceptor loads var to model(FooInterceptorSpec.groovy:9)
4

1 回答 1

1

在 Spec 中设置 ModelAndView 请求属性为我们解决了这个问题:

import grails.test.mixin.TestFor
import spock.lang.Specification

@TestFor(FooInterceptor)
class FooInterceptorSpec extends Specification {
    void "Test Foo interceptor loads var to model"() {
        given:
            interceptor.currentRequestAttributes().setAttribute(GrailsApplicationAttributes.MODEL_AND_VIEW, new ModelAndView('dummy', [:]), 0)

        when: "A request matches the interceptor"
            withRequest(controller: 'foo', action: 'index')
            interceptor.after()

        then: "The interceptor loads the model"
            interceptor.doesMatch()
            interceptor.model.foo == 'bar'
    }
}
于 2015-12-15T00:06:10.733 回答