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 org.company.service.export.ExportRequest.<init>(Lorg/company/service/export/ExportRequest$Builder;)V from class org.company.service.export.ExportRequest$$EnhancerByCGLIB$$1969beb7
 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)
 at org.company.service.export.RecordExporterSpec.$spock_initializeFields(RecordExporterSpec.groovy:141)

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

    ExportRequest request = Mock()

After adding objenesis, the error was resolved:

    <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib-nodep</artifactId>
        <version>2.2</version>
    </dependency>
    <dependency>
        <groupId>org.objenesis</groupId>
        <artifactId>objenesis</artifactId>
        <version>1.2</version>
    </dependency>

2 comments:

  1. Gradle (and updated) version:

    test 'org.objenesis:objenesis:2.4'

    ReplyDelete
  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

    ReplyDelete