grailsintegration-testinggrails-filters

How to write integration test for filter in grails


I have written one filter rule which I want to test using grails integration tests. Filter is

invalidAccess(controller: "home") {
    before = {
            redirect(controller: "newHome", action: "index")
            return false
    }
}

I have followed this link to write the integration test http://ldaley.com/post/392153102/integration-testing-grails-filters

It returns result as false But gives

null for redirectedUrl

instead of newHome & index method url. What am I missing here?

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( someParameter: "2", "home", "index")
        assertFalse result
        assertTrue response.redirectedUrl.endsWith(/* something */)
    }

}

Solution

  • If you want to try unit testing and need to mock some services then you can mock like:

    @TestFor(SomethingToTest)
    @Mock([FirstService, SecondService])
    class SomethingToTestSpec extends Specification {
    

    and you want integration test then try following test

    import grails.util.GrailsWebUtil
    import org.junit.After
    import org.junit.Before
    import org.junit.Test
    
    class MyFilterIntegrationTests {
    
        def filterInterceptor
        def grailsApplication
        def grailsWebRequest
    
        @Before
        void setUp() {
        }
    
        @After
        void tearDown() {
        }
    
        @Test
        void testFilterRedirects() {
            def result = request("person", "index", someParameter: "2")
            assert !result
            assert response.redirectedUrl.endsWith('/auth/index')
        }
    
        def getResponse() {
            grailsWebRequest.currentResponse
        }
    
        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)
        }
    }
    

    Ref# Grails Integration Test Filter