How to mock HttpServletRequest in Spock

We have a ServletFilter that we want to test with Spock and test calls on the 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 therefore the servlet API) is in the classpath. The Spock version is 0.6- groovy -1.8.

How will we do it right? He works with Mokito, but we will lose Spock, mocking awesomeness.

Editing: We know about Grails and Spring built-in mocking capabilities for Servlet stuff, we just wanted to know if there is a way to do this with Spock's mockery. Otherwise, you will have a mixture of mocking customization methods ...

+4
source share
2 answers

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

In unit test, you need to import and create new MockHttpServletRequest .

 import org.springframework.mock.web.MockHttpServletRequest def "some meaningless test"(){ given: def servletRequest = new MockHttpServletRequest() when: 1+1 then: true } 
+3
source

Spock uses dynamic JDK proxies for mocking interfaces and CGLIB for mocking classes. Mockito uses CGLIB for both. This seems to be relevant in some situations where interfaces (e.g. javax.servlet.http.HttpServletRequest ) are referenced by reference classes (e.g. javax.servlet.http.Cookie ). Apparently, in the case of Spock, the Cookie class is loaded, which leads to an error loading the class, because the classes in the servlet API do not have method bodies (and not empty method bodies).

Spock does not currently provide a way to enforce CGLIB for interfaces. This means that you can either put the servlet JLS implementation, and not the Jar API, in the test class path (which is probably a safer bet) or use Mockito.

+2
source

Source: https://habr.com/ru/post/1414333/


All Articles