Wednesday, August 13, 2008

Grails Controller Tests: ModelAndView

I just joined the team at and my first task was to revitalize the integration test for a bunch of controllers. But Grails no longer seems to have the modelAndView as a standard attribute of a controller. And we have assertions like:

assert controller.modelAndView.model.contractList.size() > 1

My solution was to override the controller's render method and stuff in a modelAndView to the controller myself:

import org.springframework.web.servlet.ModelAndView

class IntegrationTestUtil {
void overrideRender(controller) {
def dir =, '')
dir = dir[0].toLowerCase() + dir.substring(1)
def originalRender =
controller.metaClass.getMetaMethod("render", [Map] as Class[])
controller.metaClass.render = { Map args ->
if(args.view && args.model) {
delegate.metaClass.getModelAndView = {->
new ModelAndView("/${dir}/${args.view}", args.model)
} else {
originalRender.invoke(delegate, args)

My controllers then invoke the overrideRender method in setUp and the test run fine.

Note the override only changes render invocations that pass a map with model and view entries.

No comments: