MockClassLoader cannot access jdk/internal/reflect superclass jdk.internal.reflect.MagicAccessorImpl

Saif Masadeh picture Saif Masadeh · May 21, 2018 · Viewed 18.9k times · Source

I am in the middle of migrating a project into Java9, The Tests start failing after I switched to the new Java version, it seems like PowerMock is trying to access some classes it does not have access to.

Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.973 sec <<< FAILURE! - in com.Test
initializationError(com.Test)  Time elapsed: 0.007 sec  <<< ERROR!
org.objenesis.ObjenesisException: java.lang.reflect.InvocationTargetException
Caused by: java.lang.reflect.InvocationTargetException
Caused by: java.lang.IllegalAccessError: class jdk.internal.reflect.ConstructorAccessorImpl loaded by org/powermock/core/classloader/MockClassLoader cannot access jdk/internal/reflect superclass jdk.internal.reflect.MagicAccessorImpl

maven-surefire-plugin

<plugin>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.19.1</version>
    <configuration>
        <includes>
            <include>**/*Test.java</include>
            <include>**/*Test.groovy</include>
            <include>**/*Spec.*</include>
        </includes>
        <forkMode>always</forkMode>
        <argLine>--add-modules java.xml.bind</argLine>
        <argLine>--add-modules java.activation</argLine>
        <argLine>--add-opens=java.base/java.lang=ALL-UNNAMED --illegal-access=warn</argLine>
    </configuration>
</plugin>

powermock dependency

<dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-module-junit4</artifactId>
        <version>1.7.4</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-api-mockito</artifactId>
        <version>1.7.4</version>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.mockito</groupId>
                <artifactId>mockito-all</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

Answer

smac89 picture smac89 · Oct 11, 2019

I had a test dependency on a third-party jar which used powermock. In order to resolve this error, I had to add:

@PowerMockIgnore("jdk.internal.reflect.*")

To the class that is tested with powermock