grails - 集成测试Grails REST Controller

标签 grails groovy

我正在尝试为处理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/

相关文章:

grails - 有没有像 Grails 那样的 Django 上下文处理器?

grails - 在文件中未生成日志

grails - Grails Spring Security session.user为空

Grails-在 EasyB 场景中编写 Selenium 代码

java - 将 map 的值与 groovy 中的另一个 map 值进行比较

按值对 map 内的 map 进行排序

java - 如何将 java.lang.Long 添加到用于测试的 GroovyScript

grails - Grails如何根据变化的搜索参数动态搜索

mongodb - 初始化应用程序时出错 : No datastore implementation specified Message: No datastore implementation specified

grails - 为什么grails的acegi插件在weblogic中不起作用?