我在使用Grails 3(更具体的Grails 3.1.3)的控制器集成测试方面遇到了问题。
正如文档所述,现在建议测试控制器创建一个Geb功能测试,但是将我所有的控制器测试转换为Geb是一项艰苦的工作。
我尝试使用注释@Integration
转换测试并扩展GebSpec
。
我遇到的第一个问题是模拟GrailsWeb,但是GrailsWebMockUtil.bindMockWebRequest(ctx)
我解决了它(是ctx
和类型WebApplicationContext
的对象)。
现在,问题是控制器呈现某些内容或重定向到另一个操作/控制器。到目前为止,我在setupSpec阶段解决了这个重写渲染或重定向方法:
controller.metaClass.redirect = { Map map ->
redirectMap = map
}
controller.metaClass.render = { Map map ->
renderMap = map
}
但这不起作用,因为当您尝试在renderMap
或redirectMap
阶段获得then
或expect
时,这些都是空的。
有谁知道什么是解决方案?
编辑(澄清):
我编辑我的问题以澄清问题:
非常感谢您的回复@JeffScottBrown。正如我所提到的,这个解决方法是在Grails 3中解决控制器测试作为集成测试的问题,尝试转换我们在Grails 2.x中进行的所有测试。 我知道最好的解决方案是将其作为单元测试或功能测试,但我想知道是否有一个“简单”的解决方案来保持它与Grails 2.x版本一样。
我附上了我显示我想做的小project。在这个项目中,Controller有两个动作。一个操作呈现模板,另一个操作呈现视图。
在测试中,如果我检查呈现模板的操作,则modelAndView
对象为空。这就是我在展示时覆盖render
和redirect
的原因。
答案 0 :(得分: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'
}
}