2015-12-15 115 views
0

我有一個攔截器在模型對象上設置一個屬性。在單元測試中,模型爲空。Grails攔截器模型在單元測試中爲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) 

回答

0

設置在規格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' 
    } 
}