Saturday, March 21, 2009

Integration test of Grails controller

The general pattern to test a controller is:

void testBar() {
def ctrl = new FooController()
def testParams = ...

Different outcomes are expected from the call to the action:


If redirection is expected, the redirected URL can be obtained from ctrl.response.redirectedUrl. Keep in mind that unless GRAILS-4270 is resolved, you will have to make sure that the controller name is specified in the parameter list of redirect(). For example,

def index = {
redirect(action: 'list', params: params)

won't work. You need to change it to:

def index = {
redirect(controller: 'foo', action: 'list', params: params)

A View Is Rendered

If a view is expected, the parameters passed to render() is actually stored in Spring's ModelAndView object. E.g. if you have the following statement in your controller:

render(view: 'show', model: [ fooInstance: foo ])

You can access foo via:

def foo = ctrl.modelAndView.model.fooInstance

Text Is Rendered Directly

If the action renders some texts directly, the texts can be accessed by

def text = ctrl.response.contentAsString

A Map Is Returned

If a map is returned, as is the case for the scaffolded list action, you can access the map like this:

def map = ctrl.list()

Thursday, March 12, 2009

Groovy wrapper for Snipplr API

I created a Groovy wrapper for Snipplr API this afternoon. It is called, rather boringly, gsnipplr. I wanted to try out Groovy's XMLRPC module and use Maven to build the Groovy project. I threw in quite a comprehensive set of tests (IMO) and had a lot of fun playing with the testing code.

A lot of ideas were taken from arcturus' SnipplrPy. Thanks for the great example!

The source code is hosted at

To check out:

hg clone