Group testing provided by Json with JsonBuilder in Grails

Let's say I have a simple action in my controller that ends with:

render(contentType: "text/json") { message = 'some text' foo = 'bar' } 

It displays correctly, according to the JSON documentation. However, when I try to execute the unit test this answer in ControllerUnitTest, I get an empty string with controller.response.contentAsString . I even tried controller.renderArgs , but it just contains contentType: "text/json" .

When I convert JSON to a map and sort it as JSON , then I can check it correctly. But is there a way to unit test the code in its current form?

+4
source share
3 answers

After a long search, I found that this is not possible in 1.3.7. Either you need to upgrade to Grails 2.0, or redefine the metaClass controller, 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 } } 
0
source

you need to trigger an action in your tests and compare the results using controller.response.contentAsString

so your testing method will look like

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

Source: https://habr.com/ru/post/1403101/


All Articles