1

I'm trying to test a filter in Grails 2.2.1 that stores a value in the global session object anytime somebody hits any URL in my application. Here's what I came up with, thanks to this fine post:

package drummer

class SessionExpirationFilters {

    def filters = {
        all(controller: '*', action: '*') {
            before = {
                session.foo = 'bar'
            }
        }
    }
}

I'm able to see that the filter works by outputting session.foo in a controller method, but the integration test fails:

package drummer

import grails.plugin.spock.IntegrationSpec

class QuestionControllerIntegrationSpec extends IntegrationSpec {

    def 'filter sets session foo to bar'() {
        given:
        def controller = new QuestionController()

        when:
        controller.list()

        then:
        assert 'bar' == controller.session.foo // fails, session.foo is null
    }
}

So why isn't the 'foo' session object property set in the integration test?

4

1 回答 1

1

它没有被调用的原因是因为过滤器不会在控制器测试中自动运行。如果您的过滤器在服务/实用程序中,您可以为此编写单独的测试。

如果你想直接测试你的过滤器,Luke Daley 在这里写了一篇关于为过滤器创建集成测试的博客文章:

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 */)
    }    
}
于 2014-05-08T16:13:01.457 回答