json - Grails 2.3 Controller 方法返回 JSON 在单元测试中返回 null

标签 json unit-testing grails

让我首先说明 Grails 2.2 中存在完全相同的问题。我在工作时在 Windows 7 上运行 Grails 2.2,在家里我通过 Homebrew 安装在 OSX 10.8.4 上运行 Grails 2.3。两种情况都会发生相同的问题。我的 Controller 看起来像这样:

package play

import grails.converters.JSON

class HelloJsonController {

    def greet() { 
        def greeting = new Greeting(greeting: 'Hey there')
        render greeting as JSON
    }
}

我的 POGO(上面使用的)就是这样的:

package play

class Greeting {
    String greeting
}

单元测试——我知道它应该失败但由于错误的原因而失败是这样的:

package play

import grails.test.mixin.TestFor
import spock.lang.Specification

@TestFor(HelloJsonController)
class HelloJsonControllerSpec extends Specification {

    def setup() {
    }

    def cleanup() {
    }

    void "test that the controller can greet in JSON"() {
        when: 'you call the greet action'
        def resp = controller.greet()
        then: 'you should get back something nice, like a pony'
        resp == 'pony'
    }
}

当然,我预计此测试会失败,因为字符串“pony”与我返回的内容不匹配。但是,我遇到的失败不是因为这个,而是因为 null 回来了。然后,如果我运行该应用程序并转到 URL,我将返回 json 和我希望每个 Firebug 跟踪的字符串。现在,我可以像这样修改 Controller 来修复单元测试:

def greet() { 
    def greeting = new Greeting(greeting: 'Hey there')
    greeting as JSON
}

这会产生预期的输出:

resp == 'pony'
|    |
|    false
{"greeting":"Hey there"}

但是,如果我导航到该 URL,它现在会失败并显示 404。我发现它唯一的“修复”是模拟单元测试 Controller 的内容处理程序。该文档说这应该都有效......或暗示它。

这种类型的 Controller 应该像最初编写的那样是可单元测试的吗?

最佳答案

render 直接写入响应 - 参见 here .

像这样尝试:

void "test that the controller can greet in JSON"() {
    when: 
    controller.greet()

    then:
    response.text == '{"greeting":"Hey there"}'
    response.json.greeting == "Hey there"  //another option
}

关于json - Grails 2.3 Controller 方法返回 JSON 在单元测试中返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19018363/

相关文章:

java - 在 Lucene 中索引多级 JSON 对象

grails - 为什么 grails 在表单中添加一个隐藏的复选框——它的用途是什么?

javascript - yeoman gulp-angular projekt 设置后单元测试出错

angularjs - 在grails 2.3.4中加载angularjs

grails - 如何将变量从布局文件传递到 grails 模板?

javascript - 如何在 AngularJS ng-repeat 中对 Json 数组值求和

java - 通过继承将 JSON 反序列化为 Java 对象?

javascript - 使用 JSON 提供测验答案的简洁方法

python - 如何对设置内部数据但不返回的方法进行单元测试?

c# - 单元测试 IExtension<OperationContext> 以用于 WCF 服务