other register

Monday, November 15, 2010

Grails Controller Unit Test with setting params as a map

When running controller unit test. Setting the params individually like below works fine

controller.params.firstname = 'joe'
controller.params.lastname = 'blog'

However, if setting the params using a map like below:

controller.params = [firstname: 'joe', lastname: 'blog']

It would throw exceptions:

groovy.lang.ReadOnlyPropertyException: Cannot set readonly property: params for class:

As suggested by Richard Bradley and Amit Jain in Grails mailing list, there are two solutions:

With groovy meta programming:

controller.metaClass.getParams { ->
 [firstname: 'Joe', lastName: 'blog']

Or use the putAll on the params:

Map myParams = [firstname: 'joe', lastname: 'blog']

No comments: