Grails Integration Test Filter

2020-07-16 09:25发布

Is there a way to test a controller which uses a filter on an integration test?

There seems to be a way using the @Mock annotation for Unit Tests and than wrapping the controller call on a withFilter closure.

But I can't get to test filters on an integration test which from my pov should be very straight forward.

Update

So here is the solution I found. Instead of using the @Mock annotation, I instantiated the FiltersUnitTestMixin class and populated it with the necessary values.

public class ControllerTest {  

    def controller = new Controller()  
        FiltersUnitTestMixin f = new FiltersUnitTestMixin()

    @Before
    public void setup() {
        f.grailsApplication = grailsApplication
        f.applicationContext = grailsApplication.mainContext
        f.mockFilters(ControllerFilters)
    }

    @Test
    public void shouldPassTheTest() {
        f.withFilters(action:"actionName") {
            controller.actionName()
        }
    }
}

1条回答
倾城 Initia
2楼-- · 2020-07-16 09:29

I had the same issue, I found this -> http://ldaley.com/post/392153102/integration-testing-grails-filters

And modified it to suit my needs ending with this

import grails.util.GrailsWebUtil
import org.junit.After
import org.junit.Before
import org.junit.Test

class SomethingIntegrationTests {

    def filterInterceptor
    def grailsApplication
    def grailsWebRequest

    @Before
    void setUp() {

    }

    @After
    void tearDown() {

    }

    @Test
    void testFilterRedirects() {

        def result = request("home", "index", someParameter: "2")
        assert !result
        assert response.redirectedUrl.endsWith(/* something */)
    }

    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)
    }
}
查看更多
登录 后发表回答