Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Runtime Exception Mocking groovy.sql in Spock

I've scoured around StackOverflow and Google for a while trying to find the right configuration/syntax for being able to run this code in a Spock Specification:

Sql mockSql = Mock()

However when I run the unit test, I get a nasty exception thrown in my face by CGLIB:

java.lang.IllegalAccessError: tried to access method groovy.sql.Sql.<init>()V from class groovy.sql.Sql$$EnhancerByCGLIB$$d0b7cd7f
at org.spockframework.mock.runtime.MockInstantiator.instantiate(MockInstantiator.java:33)
at org.spockframework.mock.runtime.ProxyBasedMockFactory$CglibMockFactory.createMock(ProxyBasedMockFactory.java:92)
at org.spockframework.mock.runtime.ProxyBasedMockFactory.create(ProxyBasedMockFactory.java:49)
at org.spockframework.mock.runtime.JavaMockFactory.create(JavaMockFactory.java:51)
at org.spockframework.mock.runtime.CompositeMockFactory.create(CompositeMockFactory.java:44)
at org.spockframework.lang.SpecInternals.createMock(SpecInternals.java:47)
at org.spockframework.lang.SpecInternals.createMockImpl(SpecInternals.java:282)
at org.spockframework.lang.SpecInternals.MockImpl(SpecInternals.java:83)

I looked at this question/answer - Mock static method with GroovyMock or similar in Spock - hoping it might give me a good starting point, but the class being mocked in my case, groovy.Sql IS a groovy class, so I'm not sure it's the right place to start.

I've successfully tested Groovy.Sql in other unit tests using GroovyMock, but I was hoping maybe I just missed something that can make it so that I can have Spock magic and Groovy SQL all happy together. My apologies if I just missed the answer somewhere - hopefully I'm not repeating someone else's inquiry.

like image 382
Jason Lowenthal Avatar asked Jun 10 '14 18:06

Jason Lowenthal


1 Answers

When mocking classes (rather than interfaces) with Spock, putting objenesis-1.2 or higher on the test runtime class path is recommended (in addition to CGLIB) . Otherwise, Spock won't be able to avoid executing the constructor of the class to be mocked, which may have undesired side effects.

like image 126
Peter Niederwieser Avatar answered Oct 30 '22 08:10

Peter Niederwieser