2013-03-28 214 views
1

我正在嘗試爲處理JSON格式的REST請求的控制器編寫一些集成測試。我的控制器定義()創建這樣的:集成測試Grails REST控制器

class FooController { 
    ... 
    def create() { 
     withFormat { 
      html { 
       [fooInstance: new Foo(params)] 
      } 
      json { 
       [fooInstance: new Foo(params.JSON)] 
      } 
     } 
    } 
    ... 
} 

然後,我有一個集成測試,看起來像這樣:

@TestFor(FooController) 
class FooControllerTests extends GroovyTestCase { 
    void testCreate() { 
     def controller = new FooController() 

     controller.request.contentType = "text/json" 

     // this line doesn't seem to actually do anything 
     controller.request.format = 'json' 

     // as of 2.x this seems to be necessary to get withFormat to respond properly 
     controller.response.format = 'json' 

     controller.request.content = '{"class" : "Foo", "value" : "12345"}'.getBytes() 

     def result = controller.create() 

     assert result 

     def fooIn = result.fooInstance 

     assert fooIn 
     assertEquals("12345", fooIn.value) 
    } 
} 

但fooIn總是空。如果我調試測試,我可以看到當調用FooController.create()時,params也是空的。誠然,我不太瞭解集成測試如何在內部運行,但我期望看到代表我的Foo實例的數據。

任何想法?

回答

0

您使用withFormat來呈現您的內容,因此雖然它是控制器代碼中的映射,但實際上該響應是一個String。

AbstractGrailsMockHttpServletResponse提供你所需要的(以及其他有用的方法一起)和controller.response是在測試過程中一個的這個實例:

http://grails.org/doc/2.1.0/api/org/codehaus/groovy/grails/plugins/testing/AbstractGrailsMockHttpServletResponse.html#getJson()

所以,你要的是這樣的:

controller.create() 

def result = controller.response.json 

編輯:

當你問,你應該傳遞你的參數是這樣的:

controller.params.value = "12345" 
controller.params.'class' = "Foo" 
+0

我試着用你的建議,但它看起來像controller.response是空的(零長度)。在FooController.create()中進行調試和打破顯示params.JSON也是空的,所以看起來好像我在傳遞請求內容時一定有問題? – Nick

+0

我更新了我的答案,並解決了'params' – Rhysyngsun

+0

這讓我更加接近確定。你知道一種方法來獲取一個Domain對象的實例(在我的情況下是Foo),然後將它編組爲params以供controller.create()使用? – Nick