Unit testing parameters in forward method

21 / Apr / 2014 by Neha Gupta 0 comments

I always wanted to test the parameters being passed in the forward method in a controller in my unit tests.
Suppose we have any controller like:

class DemoController {
def anyAction() {
 forward(controller: "demo", action: "test", params: [param1: "1"])
}
}

to test this forward action, we first need to mock the forward method.

To do so, all we require is:

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

to be added in the setup.

To test the params, all we need to do is:

fwdArgs.params.param1
fwdArgs.controller=='demo'
fwdArgs.action=='test'

Using this we would be able to test the params being passed in the forward method.

Here is the complete test case :

@TestFor(DemoController)
class DemoControllerSpec extends Specification {

void "test anyAction"() {
 setup:
 def fwdArgs
 controller.metaClass.forward = { Map map ->
 fwdArgs = map
 }

when:
 controller.anyAction()

then:
 fwdArgs.params.param1
 fwdArgs.controller=='demo'
 fwdArgs.action=='test'

}
}

 

FOUND THIS USEFUL? SHARE IT

Leave a comment -