首先我要说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。唯一的“修复”我发现它模拟单元测试的控制器的内容处理程序。文档说这应该全部工作......或暗示它。
这种类型的控制器应该是最初编写的单元可测试的吗?
答案 0 :(得分:7)
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
}