4

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?

Igor
  • 33,276
  • 14
  • 79
  • 112

3 Answers3

0

you have to call the action in your tests and compare the results using controller.response.contentAsString

so your test method would look like

void testSomeRender() {
controller.someRender()
assertEquals "jsonString", controller.response.contentAsString

}
allthenutsandbolts
  • 1,513
  • 1
  • 13
  • 34
  • I've tried this, but like I mentioned, I just get a blank string (or it contains "contentType: 'text/json'", I can't remember off the top of my head) – Igor Apr 10 '12 at 17:19
  • I just added a code for an action which return the JSON string like you are trying to do and I don't see any content. So the issue is with content not being rendered. What version of Grails are you using ? – allthenutsandbolts Apr 10 '12 at 17:26
  • 1.3.7, I know 2.0 has better support, but unfortunately I can't switch to that. :-\ – Igor Apr 10 '12 at 17:29
  • 1.3.7 is a stable release than 2.0. 2.3 wasn't suppose to be out till oct and they are already out with the bug fixes. I think that the JSON convertor doesn't convert any String objects to JSON and hence its returning empty string. One thing which I tried was created a Expando Object and added properties to it and then rendered it and it worked. I think you should try that. Hope that helps – allthenutsandbolts Apr 10 '12 at 17:46
0

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
    }
}
Igor
  • 33,276
  • 14
  • 79
  • 112
0

Take a look at this blog post http://www.lucasward.net/2011/03/grails-testing-issue-when-rendering-as.html

gis_wild
  • 464
  • 8
  • 24