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

后端 未结 4 850
无人共我
无人共我 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:21

    You might want to rethink the project design you're trying to implement. Since you are implementing a module and its test into a project, you shall refrain from using different modules for each of them individually.

    There should just be one single module-info.java for a module and its corresponding tests.

    Your relevant project structure might look like this:-

    Project/
    |-- pom.xml/
    |
    |-- src/
    |   |-- test/
    |   |   |-- com.acme.project
    |   |   |        |-- com/acme/project
    |   |   |        |      |-- SomeTest.java
    |   |   
    |   |-- main/
    |   |   |-- com.acme.project
    |   |   |    |-- module-info.java
    |   |   |    |-- com/acme/project
    |   |   |    |    |-- Main.java
    

    where the module-info.java could further be:-

    module com.acme.project {
        requires module1;
        requires module2;
        // requires junit; not required using Maven
    }
    

    Just to sum all of the above as per your questions --

    I feel I follow wrong path, it all starts looking very ugly. How can I have module-info.java of its own in test code, or how do I achieve the same effects (require, etc) without it?

    Yes, you should not consider managing different modules for test code making it complex.

    You can achieve similar effect by treating junit as a compile-time dependency using the directives as follows-

    requires static junit;
    

    Using Maven you can achieve this following the above-stated structure and using maven-surefire-plugin which would take care of patching the tests to the module by itself.

提交回复
热议问题