Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails Integration Test Filter

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()
        }
    }
}
like image 495
Guilherme Santos Avatar asked Nov 12 '22 21:11

Guilherme Santos


1 Answers

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)
    }
}
like image 109
TBAR Avatar answered Dec 10 '22 08:12

TBAR