我正在尝试为处理JSON格式的REST请求的 Controller 编写一些集成测试。我的 Controller 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始终为null。如果我调试测试,我可以看到调用FooController.create()时,params也为空。诚然,我对集成测试如何在内部运行并不了解,但是我希望看到代表我的Foo实例的数据。
有任何想法吗?
最佳答案
您正在使用withFormat
呈现内容,因此尽管它是 Controller 代码中的映射,但响应实际上是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"
关于grails - 集成测试Grails REST Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15687177/