As Erik has explained, the solution has two steps:
- All the test sources and code of module B (everything under B's
src/test/*
) should be packed into a special artifact "test-jar". This can be done by configuring the jar plugin
Put the following into B's pom.xml
file:
<project>
...
<build>
<plugins>
...
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<goals>
<goal>test-jar</goal>
</goals>
</execution>
</executions>
</plugin>
...
</plugins>
</build>
...
</project>
Now when you package B in its target
directory you'll find two jars - one for regular sources (this one goes to production) and the one with tests
- Now A should depend on this B's test jar regardless the regular dependency of
A depends on B
. Since maven has a concept of scopes, in this case A should depend on test-b in the scope of "test" so that this test-b artifact won't propagate to production (its not transitive if A by itself is a Jar and maven from add the test-b into, say WAR, if A is a war for example). So you place the following in the A's pom.xml this time:
<dependencies>
<!-- You should already have a regular dependency on B: -->
<dependency>
<groupId><GROUP_ID_OF_B_GOES_HERE></groupId>
<artifactId><ARTIFACT_ID_OF_B_GOES_HERE></artifactId>
<version><VERSION_GOES_HERE></version>
</dependency>
<!-- Add the following dependency: -->
<dependency>
<groupId><GROUP_ID_OF_B_GOES_HERE></groupId>
<artifactId><ARTIFACT_ID_OF_TEST_B_GOES_HERE></artifactId>
<version><VERSION_GOES_HERE></version>
<scope>test</scope> <!-- this is the scope I was talking about, test-b is visible to a only during the tests -->
</dependency>
...
</dependencies>
Of course fill the placeholders its just an example.