Fork me on GitHub

LD.

Music, software, life… and stuff.

[ Twitter ] [ GitHub ] [ Linked In ]

Integration Testing Grails Filters

Grails currently doesn’t ship with any support for testing filters, other than via a functional test. It’s pretty easy to roll your own filter integration tests though.

Here is an example:

import grails.util.GrailsWebUtil

class MyFilterTests extends GroovyTestCase {
    
    def filterInterceptor
    def grailsApplication
    def grailsWebRequest
    
    def request(Map params, controllerName, actionName) {
        grailsWebRequest = GrailsWebUtil.bindMockWebRequest(grailsApplication.mainContext)
        grailsWebRequest.params.putAll(params)
        grailsWebRequest.controllerName = controllerName
        grailsWebRequest.actionName = actionName
        filterInterceptor.preHandle(grailsWebRequest.request, grailsWebRequest.response, null)
    }
    
    def getResponse() {
        grailsWebRequest.currentResponse
    }
    
    def testFilterRedirects() {
        def result = request("home", "index", someParameter: "2")
        assertFalse result
        assertTrue response.redirectedUrl.endsWith(/* something */)
    }
    
}

Note that filterInterceptor.preHandle() executes all of your filters, which is what you really want in an integration test. It also returns the return value of the last executed filter. When issuing a redirect, we return false in our filter handler to prevent any further request processing so we are testing for that here.

If you are interesting in unit testing your filters, you might want to check out the mailing list thread on the topic.

Posted: Feb 16th, 2010 @ 3:54 pm

Tags: #grails  #software  

Comments

Archive · RSS · Theme by Autumn