Mockito, Java 9 and java.lang.ClassNotFoundException: sun.reflect.ReflectionFactory

前端 未结 3 1390
广开言路
广开言路 2020-12-10 14:52

My project is a Wildfly 13 application which uses Mockito testing library. The app is not using Java 9 module structure. As long as the server ran on Java 8 the tests worked

相关标签:
3条回答
  • 2020-12-10 15:21

    As of Java 11, WildFly 14+ and Mockito 2.23.0+, adding jdk.unsupported module dependency to your WAR solves the problem. You can do this in two ways:

    A. META-INF/MANIFEST.MF

    Add the following line to META_INF/MANIFEST.MF of your WAR archive:

    Dependencies: jdk.unsupported
    

    Note that the file must end with a new line or carriage return.

    Here is how you'd typically do it with ShrinkWrap/Arquillian:

    @Deployment
    public static WebArchive createDeployment() {
        return ShrinkWrap.create(WebArchive.class, "my-app.war")
            .addPackages(true, Mockito.class.getPackage(), Objenesis.class.getPackage(), ByteBuddy.class.getPackage())
            .addAsManifestResource(new StringAsset("Dependencies: jdk.unsupported\n" /* required by Mockito */), "MANIFEST.MF");
    }
    

    B. WEB-INF/jboss-deployment-structure.xml

    Add the following content to WEB-INF/jboss-deployment-structure.xml of your WAR archive:

    <jboss-deployment-structure>
      <deployment>
        <dependencies>
          <module name="jdk.unsupported" />
        </dependencies>
      </deployment>
    </jboss-deployment-structure>
    
    0 讨论(0)
  • 2020-12-10 15:25

    I think that the problem might be that you are using an early version of Java 9. In some of the early access versions, there were issues accessing the sun.reflect library. Try updating your version of Java 9 to a later version that comes after version 9-ea+115 as recommended in this answer to a similar (albeit different) question.

    0 讨论(0)
  • 2020-12-10 15:34

    With more digging I found the solution at https://developer.jboss.org/thread/278334 which pointed me to https://docs.jboss.org/author/display/WFLY10/Class+Loading+in+WildFly. The article has a section titled "Accessing JDK classes" which states that not all classes are available to deployment by default, and you need to add them to jboss-deployment-structure.xml to make them available.

    In my case:

    <jboss-deployment-structure xmlns="urn:jboss:deployment-structure:1.1">
        <deployment>
            <dependencies>
                <system export="true">
                    <paths>
                        <path name="sun/reflect"/>
                    </paths>
                </system>
            </dependencies>
        </deployment>
    </jboss-deployment-structure>
    

    This solution works for

    • Wildfly 13, running on Java 10.0.2 (9.0.4 worked too)
    • app compiled with Java 8
    • Mockito 1.10.19 (I tried 2.20.0 but there were new errors)
    0 讨论(0)
提交回复
热议问题