Search code examples
javamockito

Mockito Inaccessible Object exception while creating a mock object


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

Solution

  • 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'
         }