Let's say I have a simple action in my controller that ends with:
render(contentType: "text/json") {
message = 'some text'
foo = 'bar'
}
It renders correctly, as per the JSON builder documentation. However, when I attempt to unit test that response in a ControllerUnitTest, I get a blank string with controller.response.contentAsString
. I even tried controller.renderArgs
, but that just contains contentType: "text/json"
.
When I convert the JSON to a map, and marshall it as JSON
, then I can test properly. But is there a way to unit test the code as it stands?
After much searching, I found that this is not possible in 1.3.7. Either have to upgrade to Grails 2.0, or override the controller metaClass as suggested in this post:
controller.class.metaClass.render = { Map map, Closure c ->
renderArgs.putAll(map)
switch(map["contentType"]) {
case null:
break
case "application/xml":
case "text/xml":
def b = new StreamingMarkupBuilder()
if (map["encoding"]) b.encoding = map["encoding"]
def writable = b.bind(c)
delegate.response.outputStream << writable
break
case "text/json":
new JSonBuilder(delegate.response).json(c)
break
default:
println "Nothing"
break
}
}