How to mock HttpServletRequest in Spock

groovy, java, mocking, servlets, spock

Solution

Grails automatically configures each integration test with a `MockHttpServletRequest`, `MockHttpServletResponse`, and `MockHttpSession` that you can use in your tests.

In a unit test you need to import and instantiate a new MockHttpServletRequest.

import org.springframework.mock.web.MockHttpServletRequest

def "some meaningless test"(){
    given:
    def servletRequest = new MockHttpServletRequest()

    when:
    1+1

    then:
    true
}

Problem

We have a ServletFilter we want to unit tests with Spock and check calls to HttpServletRequest. The following code throws `java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/servlet/http/Cookie` ``` def "some meaningless test"(){ given: HttpServletRequest servletRequest = Mock(HttpServletRequest) when: 1+1 then: true } ``` The JavaEE 5 API (and thus the Servlet API) is on the classpath. The Spock version is 0.6-groovy-1.8. How would we do that right? It works with Mockito but we'd loose the Spock mocking awesomeness. Edit: We know about Grails and Spring built-in mocking capabilities for Servlet stuff, we'd just like to know if there's a way to do it with Spock mocking. Otherwise you'd have a mix of mocking setup techniques...

Original source