我正在嘗試爲處理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實例的數據。
任何想法?
我試着用你的建議,但它看起來像controller.response是空的(零長度)。在FooController.create()中進行調試和打破顯示params.JSON也是空的,所以看起來好像我在傳遞請求內容時一定有問題? – Nick
我更新了我的答案,並解決了'params' – Rhysyngsun
這讓我更加接近確定。你知道一種方法來獲取一個Domain對象的實例(在我的情況下是Foo),然後將它編組爲params以供controller.create()使用? – Nick