Grails controller test containing model statements when rendering a template?

Using Grails 2.1.0

It seems to do this from the controller:

render(view: "someView", model: [modelEntry: "hello"]) 

allows me to do this in unit test for this controller:

controller.method() 
assert model.modelEntry == "hello" 

However, if I change the controller, do this:

render(template: "someTemplate", model: [modelEntry: "hello"]) 

Now the model instance in the test is an empty array. I understand this a lot, and most of the solutions seem to be for Grails 1, often involving an object modelAndView(which is not in my test) or renderArgs(ditto).

The only solution I found was to manually override the views in the test, for example:

views['_someTemplate.gsp'] = '${modelEntry}'

and then make statements about the string. But I do not like this solution because it:

  • requires the test to know the template file name
  • makes it difficult to test model records that do not have good toString () methods
  • .

, ?

+5
1

(org.codehaus.groovy.grails.web.metaclass.RenderDynamicMethod), , modelAndView view.

AndView.

, , Groovy metaClass. , , .

, ( , , ):

@TestFor(MyController)
class MyControllerTests

  def templateModel

  @Test
  void inspectTemplateModel() {
    def originalMethod = MyController.metaClass.getMetaMethod('render', [Map] as Class[])
    controller.metaClass.render = { Map args ->
      templateModel = args.model
      originalMethod.invoke(delegate, args)
    }

    controller.method()
    assert templateModel.modelEntry == 'foo'

}
+9

All Articles