Search code examples
javamavenstructureproject-structure

Maven recommends not using test-jars, yet I would end up with a cyclic dependency


I have 2 modules in the following structure

  • lib
    • src/main/java
      • MyInterface
    • src/test/java
      • MyMockObject implements MyInterface
      • MyTest1 - uses MyMockObject
  • main dependsOn: -lib test-jar scope: test & -lib
    • src/test/java
      • MyTest2 - uses MyMockObject

Currently this was fine as my main module would add a dependency on the lib's test-jar module, however as seen here https://maven.apache.org/plugins/maven-jar-plugin/examples/create-test-jar.html It is recommended to instead create a -test module and expose that rather than using test-jars.

This however in my case would result in a cyclic dependency as follows:

  • test - dependsOn -lib
    • src/main/java
      • MyMockObject implementsMyInterface
  • lib - dependsOn: -test scope test
    • src/main/java
      • MyInterface
    • src/test/java
      • MyTest1 uses MyMockObject
  • main dependsOn: -test scope test & -lib
    • src/test/java
      • MyTest2 - uses MyMockObject

How can I keep an organised structure for maven in this case?


Solution

  • The reason for Mavens recomandation not to use test-jar dependency is

    The downside of this solution is that you don't get the transitive test-scoped dependencies automatically. Maven only resolves the compile-time dependencies, so you'll have to add all the other required test-scoped dependencies by hand.

    source

    So if that is not a problem, just use a test-jar dependency. You can also package only those test classes and resources into the test-jar that you really want to share :

                <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>test-jar</goal>
                        </goals>
                        <configuration>
                            <includes>
                            <!-- include only test resources from that package-->                               <include>**/com/prefabwarek/web/ui/page/include/*</include>
                            </includes>
                        </configuration>
                    </execution>
                </executions>
            </plugin>