Tuesday, September 8, 2009

Grails - How to execute the parameters data binding process in an integration test

When executing a request in a web application in Grails there is a process that binds the request parameters with the controller "params" object. Grails have different listeners that are notified and then execute the binding.

The class UrlMappingsFilter, which is a Servlet filter that uses the Grails UrlMappings to match and forward requests to a relevant controller and action, is the one in charge of notifying these listeners so they execute the data binding. However, this step is not executed in an integration test by default, therefore if you need to test a controller action in an integration test, you need to notify these listeners manually so the binding is done and you can access the controller "params" object inside your test. The way to do this notification is by executing the following line of code:

controller.request.getAttribute("org.codehaus.groovy.grails.WEB_REQUEST").informParameterCreationListeners()

So for example if you were using a JSON content type the listener JSONParsingParameterCreationListener would be notified and then it would do the request parameters parsing allowing you to use the controller.params object on your test.

It is important to execute this code before actually calling the controller action method that you want to test so the "params" object is available when you need it. Also, to set the controller content-type to JSON doing something like:

controller.request.content-type = "text/json"

Where controller is the instance of your controller class.

No comments:

Post a Comment