2

首先让我说 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。我发现它的唯一“修复”是模拟单元测试控制器的内容处理程序。文档说这应该都可以工作......或暗示它。

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

4

1 回答 1

7

render直接写入响应 - 请参见此处

试试这样:

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
}
于 2013-09-26T02:51:13.197 回答