Re-use your test classes across different projects
Sometimes, you need to reuse your test classes across different projects. These are two use-cases that I know of:
- Utility classes that create relevant domain objects used in different modules
- Database test classes (ans resources) that need to be run in the persistence project as well as the integration test project
Since I’ve seen more than my share of misuses, this article aim to provide an elegant solution once and for all.
Creating the test artifact
First, we have to use Maven: I know that not everyone is a Maven fanboy, but it get the work done – and in our case, it does it easily. Then, we configure the JAR plugin to attach tests. This will compile test classes and copy test resources, and package them in an attached test artifact.
org.apache.maven.plugins maven-jar-plugin 2.2 test-jar
The test artifact is stored side-by-side with the main artifact once deployed in the repository. Note that the configured
test-jar is bound to the install goal.
Using the test artifact
The newly-created test artifact can be expressed as a dependency of a projet with the following snippet:
ch.frankel.blog.foo foo 1.0.0 test-jar test
type has to be
test-jar instead of simply
jar in order to Maven to pick the attached artifact and not the main one. Also, note although you could configure the dependency with a classifier instead of a type, the current documentation warns about possible bugs and favor the type configuration.
To go further:
- Maven guide to using attached tests