How to Create a JAR With Test Classes
When you create a JAR with test classes, you probably want to reuse those classes. There are two ways to do this:
- Create an attached JAR with the test classes from the current project. This JAR does not include the transitive
test-scoped dependencies. - Create a separate project with the test classes.
The easy way
Use this configuration to produce a JAR with your test classes and resources:
<project>
...
<build>
<plugins>
...
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>4.0.0-beta-2</version>
<executions>
<execution>
<goals>
<goal>test-jar</goal>
</goals>
</execution>
</executions>
</plugin>
...
</plugins>
</build>
...
</project>
To reuse this artifact in another project, declare the dependency with type set to test-jar:
<project>
...
<dependencies>
<dependency>
<groupId>groupId</groupId>
<artifactId>artifactId</artifactId>
<classifier>tests</classifier>
<type>test-jar</type>
<version>version</version>
<scope>test</scope>
</dependency>
</dependencies>
...
</project>
This configuration generates two JAR files. The first contains the classes from src/main/java. The second contains the classes from src/test/java. The JAR names follow the schema artifactId-version.jar and artifactId-version-classifier.jar.
The values of artifactId and version come from your pom.xml file. The default classifier is tests. You can change it in the jar goal configuration.
Note: This solution does not include the transitive test-scoped dependencies automatically. Maven resolves only the compile-time dependencies. Add all other required test-scoped dependencies by hand.
The preferred way
To let Maven resolve all test-scoped transitive dependencies, create a separate project:
<project>
<groupId>groupId</groupId>
<artifactId>artifactId-tests</artifactId>
<version>version</version>
...
</project>
- Move the source files you want to share from
src/test/javain the original project tosrc/main/javain this project. Move the resources in the same way. - Move the required
test-scoped dependencies from the original project to this project. Remove theirtestscope. The test framework dependency, for example junit, gets the default scope too. Add any project specific dependencies that the code needs.
Add this dependency to use the reusable test classes in another project:
<project>
...
<dependencies>
<dependency>
<groupId>groupId</groupId>
<artifactId>artifactId-tests</artifactId>
<version>version</version>
<scope>test</scope>
</dependency>
</dependencies>
...
</project>

