【问题标题】:Grails 2.3.6 IntegrationSpec Spock test can't modify controller.request.JSON when using @StepwiseGrails 2.3.6 IntegrationSpec Spock测试在使用@Stepwise时无法修改controller.request.JSON
【发布时间】:2015-11-11 21:32:19
【问题描述】:

我在 Grails 2.3.6 中有一个 IntegrationSpec 测试,它创建任何控制器的实例,将数据添加到主体(通过 controller.request.JSON),然后验证它是否已正确设置。

问题是当我添加@Stepwise注解时,似乎将request对象锁定在controller对象上。在调试器中,我看到它是同一个对象(基于哈希码),正如您在下面的测试失败中看到的那样,第二次使用 where: 块中的值运行测试时,它失败了,因为第一次where: 块中的值仍然存在。

@Stepwise
class TestSpec extends IntegrationSpec {

    @Unroll
    void "changing controller request"() {
        setup:
        SomeController controller = new SomeController()

        when:
        controller.request.JSON = json

        then:
        controller.request.JSON == json

        where:
        json << [
                [one: "1"],
                [two: "2"]
        ]
    }
}

这是失败的消息。

controller.request.JSON == json
|          |       |    |  |
|          |       |    |  [two:2]
|          |       |    false
|          |       [one:1]
|          org.codehaus.groovy.grails.plugins.testing.GrailsMockHttpServletRequest@55906c66
com.package.SomeController@7b044602

如果我删除@Stepwise,这不会失败。

有什么方法可以强制重新创建request 对象,或者覆盖之前测试设置的值?

【问题讨论】:

  • 相信controlup.response.reset() in cleanup: in the feature方法也能解决这个问题。

标签: grails grails-2.0 spock


【解决方案1】:

永不失败 - 一个问题困扰了我几个小时,我将其发布在这里,然后找出解决方案。

所以我研究了IntegrationSpec,这是一个特定于 grails 的类,用于在集成环境中处理 Spock 规范。我注意到setupSpec()setup() 方法将通过调用initRequestEnv() 来初始化请求对象。不幸的是,只有在这不是使用 @Stepwise 进行的测试时才会发生这种情况 - 我不知道为什么。

解决方案是在测试中手动添加此检查,方法是在测试中添加以下行,这将为每个测试重新创建 request 对象。

private GrailsTestRequestEnvironmentInterceptor perMethodRequestEnvironmentInterceptor = null

def setup() {
    perMethodRequestEnvironmentInterceptor = initRequestEnv()
}

def cleanup() {
    perMethodRequestEnvironmentInterceptor?.destroy()
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 2013-09-09
    • 1970-01-01
    • 2014-09-17
    相关资源
    最近更新 更多