Unit testing parameters in forward method
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:
[java]
class DemoController {
def anyAction() {
forward(controller: “demo”, action: “test”, params: [param1: “1”])
}
}
[/java]
to test this forward action, we first need to mock the forward method.
To do so, all we require is:
[java]
def fwdArgs
controller.metaClass.forward = { Map map ->
fwdArgs = map
}
[/java]
to be added in the setup.
To test the params, all we need to do is:
[java]
fwdArgs.params.param1
fwdArgs.controller==’demo’
fwdArgs.action==’test’
[/java]
Using this we would be able to test the params being passed in the forward method.
Here is the complete test case :
[java]
@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’
}
}
[/java]