-1

我在使用 Grails 3(更具体的 Grails 3.1.3)对控制器进行集成测试时遇到问题。

正如文档所说,现在建议测试控制器以创建 Geb 功能测试,但是将我必须的所有控制器测试转换为 Geb 是一项艰巨的工作。

我试图用 annotation@Integration和 extend转换 test GebSpec

我遇到的第一个问题是模拟 GrailsWeb,但GrailsWebMockUtil.bindMockWebRequest(ctx)我解决了它(存在ctx和类型的对象WebApplicationContext)。现在,问题是当控制器呈现一些内容或重定向到另一个动作/控制器时。到目前为止,我在 setupSpec 阶段解决了这个覆盖渲染或重定向的方法:

controller.metaClass.redirect = { Map map ->
    redirectMap = map
}

controller.metaClass.render = { Map map ->
    renderMap = map
}

但这不起作用,因为当您尝试获取renderMapredirectMap进入thenexpect阶段测试时,这些都是空的。

有谁知道可能是什么解决方案?

编辑(澄清):

我编辑我的问题以澄清问题:

非常感谢您的回复@JeffScottBrown。正如我所提到的,这个解决方法是解决控制器测试作为 Grails 3 中的集成测试的问题,尝试转换我们在 Grails 2.x 中的所有测试。我知道最好的解决方案是将其作为单元测试或功能测试,但我想知道是否有一个“简单”的解决方案可以将其保持在 Grails 2.x 版本中。

我附上了我想要做的小项目。在这个项目中,控制器有两个动作。一个动作呈现模板,另一个动作呈现视图。在测试中,如果我检查呈现模板的操作,则该modelAndView对象为空。这就是我覆盖renderand的原因,redirect正如我所展示的那样。

4

1 回答 1

0

集成测试中有很多东西在集成测试中无效或不是一个好主意。我不知道您是否真的在问如何编写集成测试,或者特别是如何在示例应用程序中测试场景。在示例应用程序中测试场景的方法是使用单元测试。

// src/test/groovy/integrationtestcontroller/TestControllerSpec.groovy
package integrationtestcontroller

import grails.test.mixin.TestFor
import spock.lang.Specification

@TestFor(TestController)
class TestControllerSpec extends Specification {

    void "render the template"() {
        when:
        controller.index()

        then:
        response.text == '<span>The model rendered is: parameterOne: value of parameter one - parameterTwo: value of parameter two</span>'
    }

    void "render the view"() {
        when:
        controller.renderView()

        then:
        view == '/test/testView'
        model.parameterOne == 'value of parameter one'
        model.parameterTwo == 'value of parameter two'
    }
}
于 2016-03-17T15:14:06.453 回答