Runtime Exception Mocking groovy.sql in Spock
Asked Answered
S

1

6

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.

Subaxillary answered 10/6, 2014 at 18:54 Comment(6)
Does this work? github.com/nickmcdowall/Groovy-Examples/blob/master/… what version of Spock and groovy?Kuhns
Spock is 0.7, Groovy is 2.2.2. Sql sql = Mock(Sql) I just tried, to no avail. It seems like this may be classpath/compatibility troubles, since it seems like other people have no problem with this kind of mocking.Subaxillary
Spock spock 0.7-groovy-2.0 yeah? Can you try it in a greenfield project?Kuhns
I'll give that a shot. Correct on the dependency version.Subaxillary
Have you added objenesis to your test runtime class path?Loquacious
@peter-niederwieser Looks like objenesis was the thing. If you put that as an answer, I'll accept it and vote it up.Subaxillary
L
7

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.

Loquacious answered 12/6, 2014 at 3:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.