2016-03-15 124 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'對象?我認爲這是我原來的問題的關鍵。 非常感謝! –