Over a million developers have joined DZone.

Reuse Test Classes Across Different Projects

DZone's Guide to

Reuse Test Classes Across Different Projects

· Java Zone ·
Free Resource

Get the Edge with a Professional Java IDE. 30-day free trial.

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 aims 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 gets 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.


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 project with the following snippet:


The type has to be test-jar instead of simply jar in order for Maven to pick the attached artifact and not the main one. Also, note that although you could configure the dependency with a classifier instead of a type, the current documentation warns you about possible bugs and favors the type configuration.

Original article: http://blog.frankel.ch/re-use-your-test-classes-across-different-projects

To go further:

Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}