Модель Grails Interceptor имеет значение null в модульном тесте

У меня есть перехватчик, который устанавливает свойство объекта модели. В модульном тесте модель имеет значение null.

Перехватчик

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)

person Kevan Ahlquist    schedule 15.12.2015    source источник


Ответы (1)


Установка атрибута запроса 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'
    }
}
person Kevan Ahlquist    schedule 15.12.2015