This blogpost titled “Test forward method of Controller” explains the technique that can be used to test forward method of controller. Recently, I was writing test cases in grails to test an action :


def performAction() {

forward(controller: 'controllerName', action: params.perform ? params.perform : 'list', params: params)

}

I wrote the following test case:


when:
controller.performAction()

then:
controller.response.forwardedUrl == '/controllerName/list'

When I ran the test case it failed. The value of ‘forwardedUrl’ was ‘/grails/controllerName/actionName.dispatch’.

So in order to test it I had two ways:

  1. Parse the forwardedURL using regex(Regular Expression)

private String getForwardedUrl() {
parseResponseForwardedUrl()
}

private parseResponseForwardedUrl() {
def forwardedUrlPattern = ~/\/grails\/(.*)?\.dispatch\?*(.*)/
def matcher = controller.response.forwardedUrl =~ forwardedUrlPattern
def forwardUrl = null

if (matcher) {
forwardUrl = "/${matcher[0][1]}"
}

return forwardUrl
}

2. Using metaclass to override the behavior of controller’s forward method:

def forwardMap
controller.metaClass.forward = { Map map ->
 forwardMap= map
}

setup:
def forwardMap
controller.metaClass.forward = { Map map ->
forwardMap = map
}

when:
controller.performAction()

then:
forwardMap.controller=='controllerName'
forwardMap.action=='list'

Jira Issue related to this problem : JIRA ISSUE

That was all.
Hope it helped 🙂

Thanks