【问题标题】:Grails 2.3 controller method returns JSON gets null back in unit testGrails 2.3 控制器方法返回 JSON 在单元测试中返回 null
【发布时间】:2013-09-26 02:29:47
【问题描述】:

首先让我说 Grails 2.2 上也存在同样的问题。我在 Windows 7 上运行 Grails 2.2,在家里我通过 Homebrew 安装在 OSX 10.8.4 上运行 Grails 2.3。在这两种情况下都会发生同样的问题。我的控制器看起来像这样:

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 跟踪的字符串。现在,我可以像这样修改控制器来修复单元测试:

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

这会导致预期的输出:

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

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

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

【问题讨论】:

    标签: json unit-testing grails


    【解决方案1】:

    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
    }
    

    【讨论】:

    • 谢谢。我的错误是假设 render 将其输出返回给调用者,并且将是我的控制器操作中的最后一个表达式。所以我想我可以断言返回的值。
    猜你喜欢
    • 2022-07-27
    • 2017-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-08
    • 1970-01-01
    • 2020-06-14
    相关资源
    最近更新 更多