gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:04:17 25 4
gpt4 key购买 nike

让我首先说明 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com