How to compile test code in a modular project?
Till Brychcy
register.jigsaw at brychcy.de
Wed Nov 8 20:03:16 UTC 2017
A common source structure (e.g. used by maven and gradle) is that tests are in separate source directory with separate output directory
and are in the same packages as the code that is being tested, so the tests can access code elements that have package visibility.
Also, test dependencies like junit should not be referenced in the module-info.java, so „main" code cannot accidentally access them.
The question is, how to compile the tests with javac (version 9.0.1)?
The following example is more detailed in https://bugs.eclipse.org/bugs/show_bug.cgi?id=520713 but I think my question should
be clear without the details.
Compiling the main code is no problem (module-info.java defines module m):
javac -d target/classes src/main/java/module-info.java src/main/java/p1/*.java
I think the following would be correct according to http://openjdk.java.net/jeps/261
javac -d target/test-classes -cp target/classes --module-path junit-4.8.2.jar --add-reads m=junit src/test/java/p1/P1Test.java
but there is a warning: "warning: module name in --add-reads option not found: m" and then there are errors because junit is not found.
The following versions don't work:
javac --module=m -d target/test-classes -cp target/classes --module-path junit-4.8.2.jar --add-reads m=junit src/test/java/p1/P1Test.java
javac --module=m -d target/test-classes --module-path target/classes:junit-4.8.2.jar --add-reads m=junit src/test/java/p1/P1Test.java
Both give: "error: module source path must be specified if -m option is used"
I tried to use --module-source-path, just to have one:
javac --module=m -d target/test-classes --module-path target/classes:junit-4.8.2.jar --module-source-path src/main/java --add-reads m=junit src/test/java/p1/P1Test.java
But this gives "error: module m not found in module source path" (I guess the problem is that there is no "m" subdirectory in src/main/java)
I *can* compile the test code as follows:
javac -d target/test-classes -cp target/classes --module-path junit-4.8.2.jar --add-modules junit src/test/java/p1/P1Test.java
As I understand it, javac compiles this as part of the unnamed module, so I can e.g. use "import java.rmi.*;" in P1Test.java and no error is reported.
So this is not a "correct" solution.
Is compiling code test code (or any code to be used with --patch-module) as part of the module actually possible with javac?
More information about the jigsaw-dev
mailing list