Java 9 + maven + junit: does test code need module-info.java of its own and where to put it?

后端 未结 4 848
无人共我
无人共我 2020-12-05 06:32

Let\'s say I have a Java project using Maven 3 and junit. There are src/main/java and src/test/java directories which contain main sources and test

4条回答
  •  悲哀的现实
    2020-12-05 07:02

    Adding some details.

    In Java since 9, a jar file (or a directory with classes) may be put on classpath (as earlier), or on module path. If it is added to classpath, its module-info is ignored, and no module-related restrictions (what reads what, what exports what, etc) are applied. If, however, a jar is added to module path, it is treated as a module, so its module-info is processed, and additional module-related restrictions will be enforced.

    Currently (version 2.20.1), maven-surefire-plugin can only work in the old way, so it puts the classes being tested on classpath, and module-path is ignored. So, right now, adding module-info to a Maven project should not change anything with tests being run using Maven (with surefire plugin).

    In my case, the command line is like the following:

    /bin/sh -c cd /home/rpuch/git/my/test-java9-modules-junit && /home/rpuch/soft/jdk-9/bin/java --add-modules java.se.ee -jar /home/rpuch/git/my/test-java9-modules-junit/target/surefire/surefirebooter852849097737067355.jar /home/rpuch/git/my/test-java9-modules-junit/target/surefire 2017-10-12T23-09-21_577-jvmRun1 surefire8407763413259855828tmp surefire_05575863484264768860tmp
    

    The classes under test is not added as a module, so they are on classpath.

    Currently, a work is under way in https://issues.apache.org/jira/browse/SUREFIRE-1262 (SUREFIRE-1420 is marked as a duplicate of SUREFIRE-1262) to teach surefire plugin to put code under test on module path. When it is finished and released, a module-info will be considered. But if they will make the module under test to read junit module automatically (as SUREFIRE-1420 suggests), module-info (which is a main module descriptor) will not have to include a reference to junit (which is only needed for tests).

    A resume:

    1. module-info just needs to be added to the main sources
    2. for the time being, surefire ignores new module-related logic (but this will be changed in the future)
    3. (when modules will work under surefire tests) junit will probably not need to be added to the module-info
    4. (when modules will work under surefire tests) if some module is required by tests (and only by them), it may be added as a compile-only dependence (using require static), as suggested by @nullpointer. In this case, the Maven module will have to depend on an artifact supplying that test-only module using compile (not test) scope which I don't like much.

提交回复
热议问题