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 :
1 2 3 4 5 6 7 8 9 |
[php] def performAction() { forward(controller: 'controllerName', action: params.perform ? params.perform : 'list', params: params) } [/php] |
I wrote the following test case:
1 2 3 4 5 6 7 8 9 |
[php] when: controller.performAction() then: controller.response.forwardedUrl == '/controllerName/list' [/php] |
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:
- Parse the forwardedURL using regex(Regular Expression)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
[php] 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 } [/php] |
2. Using metaclass to override the behavior of controller’s forward method:
1 2 3 4 5 6 |
[php] def forwardMap controller.metaClass.forward = { Map map -> forwardMap= map } [/php] |
1 |
Now the test cases will be rewritten as: |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
[php] setup: def forwardMap controller.metaClass.forward = { Map map -> forwardMap = map } when: controller.performAction() then: forwardMap.controller=='controllerName' forwardMap.action=='list' [/php] |
Jira Issue related to this problem : JIRA ISSUE
That was all.
Hope it helped 🙂
Thanks
Recent Comments