unit-testing - Grails Interceptor模型在单元测试中为空

标签 unit-testing grails grails-3.0 grails-3.0.10

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

拦截器

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

关于unit-testing - Grails Interceptor模型在单元测试中为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34278853/

相关文章:

json - 从 object/json 中删除字段属性

hibernate - Hibernate OptimisticLockingFailureException应该不会抛出

grails - Grails “Cannot set readonly property”

unit-testing - 单元测试因GrailsConfigurationException失败-无法找到负责任的代码行

unit-testing - 如何使用 JUnit5 测试 OpenEJB 中的 EJB Bean?

javascript - Jasmine/Angular.js $scope 在加载 Controller 上未定义

grails - 在 grails 中运行集成测试时无法加载 ApplicationContext

grails - Grails 3.0.1-文件夹丢失了吗?

unit-testing - 如何在 test.check 中生成随机电子邮件地址?

jquery - 模拟 Ajax 失败以进行 QA 测试