我试图为处理JSON格式的REST请求的控制器编写一些集成测试。我的控制器define()创建如下:
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 :(得分:0)
您正在使用withFormat
呈现内容,因此虽然它是控制器代码中的地图,但响应实际上是一个字符串。
AbstractGrailsMockHttpServletResponse
提供了您需要的内容(以及其他有用的方法)和controller.response是测试期间的一个实例:
所以你想要的是这样的:
controller.create()
def result = controller.response.json
编辑:
正如你所问,你应该像这样传递你的参数:
controller.params.value = "12345"
controller.params.'class' = "Foo"