2016-03-15 125 views
-1

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

正如文档所述,现在建议使用测试控制器来创建一个Geb功能测试,但是要将所有控制器测试转换为Geb,这是一项艰巨的任务。

我试过用注释@Integration进行转换测试,并延伸GebSpec

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

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

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

但这不起作用,因为当你试图获得renderMapredirectMapthenexpect阶段测试,这些都是空。

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

编辑(澄清):

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

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

我附上我的小project,显示我想要做什么。在这个项目中有两个动作的控制器。一个动作呈现模板,另一个动作呈现视图。 在测试中,如果我检查呈现模板的操作,则modelAndView对象为空。这就是为什么我重写renderredirect的原因。

+0

您不应该从集成测试中调用'bindMockWebRequest'。 –

+0

“正如文档所述,现在推荐使用测试控制器来创建Geb功能测试” - 如果您想编写功能测试,建议您创建一个Geb测试。单元测试仍然应该写成单元测试,而不涉及Geb。 –

+0

在集成测试中,你不应该像'controller.metaClass.redirect = {...}一样。 –

回答

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

非常感谢您的回复;) 我有一个关于你已经显示的代码的问题,是否有可能在第一个测试中(模板的渲染模式被创建)访问'modelAndView'对象?我认为这是我原来的问题的关键。 非常感谢! –