java如何在Spock中模拟HttpServletRequest
我们有一个ServletFilter,我们想用Spock进行单元测试,并检查对HttpServletRequest的调用
下面的代码抛出
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
}
JavaEE5API(以及Servlet API)位于类路径上。Spock版本是0.6-groovy-1.8
我们该怎么做?它与Mockito一起工作,但我们将失去斯波克嘲弄的威严
编辑:我们知道Grails和Spring内置的Servlet模拟功能,我们只是想知道是否有办法用Spock模拟来实现。否则你会混合使用模拟设置技术
# 1 楼答案
Spock使用JDK动态代理模拟接口,使用CGLIB模拟类。Mockito同时使用CGLIB。在模拟接口(如
javax.servlet.http.HttpServletRequest
)引用类(如javax.servlet.http.Cookie
)的某些情况下,这似乎有所不同。显然,在斯波克的例子中,Cookie
类被加载,这会导致类加载错误,因为servlet API Jar中的类没有方法体(而不是空的方法体)目前,Spock没有提供一种强制使用CGLIB进行接口的方法。这意味着您可以将servlet实现Jar而不是API Jar放在测试类路径上(这可能是更安全的选择),或者使用Mockito