簡體   English   中英

Grails Interceptor模型在單元測試中為空

[英]Grails Interceptor model is null in unit test

我有一個攔截器,可以在模型對象上設置屬性。 在單元測試中,模型為空。

攔截器

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)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM