10

Getting a java.lang.reflect.InaccessibleObjectException while trying to Mock an object

Unable to make protected final java.lang.Class java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int,java.security.ProtectionDomain) throws java.lang.ClassFormatError accessible: module java.base does not "opens java.lang" to unnamed module @238e0d81
Kaveh
  • 1,158
  • 6
  • 16
Rohan Khanna
  • 103
  • 2
  • 5
  • 1
    I was facing similar issue with java 16, I switch to java 8, that resolved my issue. Also this is my mockito dependency org.mockitomockito-all1.10.19, check if this works for you – AbhiK Jul 15 '21 at 11:20
  • @AbhiK Same, switching from java 17 to java 15 fixed it for me. – cs_pupil Jul 18 '22 at 18:43
  • This might be helpful https://stackoverflow.com/a/74106907/2574965 – Pukhraj soni Oct 18 '22 at 07:01

1 Answers1

10

This can happen if Mockito requires reflective access to non-public parts in a Java module. If you want to stick with a newer Java version, you can get around this by explicitly allowing access via --add-opens in your java call - the error message is helpful in that it gives you both the required module and package:

java --add-opens java.base/java.lang=ALL-UNNAMED ...

(Where the target ALL-UNNAMED applies to all non-modular classes. See, e.g., https://www.oracle.com/corporate/features/understanding-java-9-modules.html for a brief introduction into these directives.)

Note that this option does not apply during compilation, i.e., not to javac; it is a runtime option.

If you are using Gradle, you can add this to the test task in your build.gradle:

    test {
         jvmArgs '--add-opens=java.base/java.lang=ALL-UNNAMED'
     }

Or, an alternative syntax to the same effect:

    test {
         jvmArgs '--add-opens', 'java.base/java.lang=ALL-UNNAMED'
     }
Hans
  • 2,419
  • 2
  • 30
  • 37
  • I have maven, what should i do – Robs May 05 '23 at 14:02
  • I am not familiar with Maven, but this sounds related: https://stackoverflow.com/questions/64920521/how-to-pass-add-opens-jdk-module-configuration-to-maven-test – Hans May 06 '23 at 12:27