Wednesday, November 5, 2014

Spock and Objenesis: Resolving IllegalAccessError

Spock and Objenesis: Resolving IllegalAccessError

When mocking some classes with Spock in one of the usual ways, we often may need to include cglib. We also have to add objensis as well.

In one our modules, the latter was removed, leading to the below type of error that did not directly point out the cause:

java.lang.IllegalAccessError: tried to access method<init>(Lorg/company/service/export/ExportRequest$Builder;)V from class$$EnhancerByCGLIB$$1969beb7
 at org.spockframework.mock.runtime.MockInstantiator.instantiate(
 at org.spockframework.mock.runtime.ProxyBasedMockFactory$CglibMockFactory.createMock(
 at org.spockframework.mock.runtime.ProxyBasedMockFactory.create(
 at org.spockframework.mock.runtime.JavaMockFactory.create(
 at org.spockframework.mock.runtime.CompositeMockFactory.create(
 at org.spockframework.lang.SpecInternals.createMock(
 at org.spockframework.lang.SpecInternals.createMockImpl(
 at org.spockframework.lang.SpecInternals.MockImpl(

For our mocking, we would define the mock at the field level like:

    ExportRequest request = Mock()

After adding objenesis, the error was resolved:



  1. Gradle (and updated) version:

    test 'org.objenesis:objenesis:2.4'

  2. Hi
    Very nice blog post!! Thanks for the post,
    That is a really neatly written article and well formatted.
    Oracle R12 Financials Online Training