Thursday, June 4, 2009

Integration Testing Grails Controllers

If you are planning on running integration tests on your Grails controllers it would be good to know how to test your controller regardless of whether it simply returns the model or uses the render method.

When your controller returns a model you can simply test the return type.


def show = {
def bookInstance= Book.get( )
return [ bookInstance: bookInstance] }

You test it by:

def model =
assertNotNull model.bookInstance

or some such.

If you use the render method in your controller then you would use the ModelAndView object in your controller.


def save = {
def bookInstance = Book.get(
render(view:'create',model: [ bookInstance : bookInstance ])

You can test it as follows:
assertNotNull bookController.modelAndView.model.bookInstance

There is one nasty caveat to the render method, and that is if you are rendering a template instead of a view. This is common when you are doing AJAX type calls that only return a partial page. The problem is that Grails will not populate the modelAndView map at all. Nor does render provide a return type.

The answer came from the following mailing list posting:

Essentially you need to alter the behavior of the render method. You can do this in the setup as follows:

def renderMap

protected void setUp() {
BookController.metaClass.render = { Map map ->
renderMap = map

Then Given:

def bookSummary = {
def bookInstance = Book.get(
render(template: "bookSummary", model: [ bookInstance : bookInstance ])

And then you test your model values as follows:

assertNotNull renderMap.model.bookInstance

I hope this is helpful.

Happy Grailing!

Monkey Search