Maven: How to Access Test classes in other Projects

Introduction

Sometimes you want to access test classes defined in one project from another project.

Most often this is because you either want:

  • to directly use test utility classes defined in another project
  • to sub-class test classes that are defined in another project

Maven provides a standard mechanism to handle this requirement, which we document below.

Create a test jar for a project

First you will need to create a jar that contains the test classes for your project. This is done by the test-jar:jar goal of the maven-jar-plugin.

To cause this goal to be automatically run as part of the package phase of the lifecycle, you will need to add the following snippet to that project’s pom.xml file:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <executions>
                <execution>
                    <goals>
                        <goal>test-jar</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
        ...
</build>

Use a test jar from one project in another project

Once you have a test jar in the repository for a project you can define a dependency on that jar in another project.

In the dependent project’s pom.xml file, you will need to specify a dependency like the following:

<dependency>
    <groupId>my.artifact.group.id</groupId>
    <artifactId>my-artifact-id</artifactId>
    <version>1.2</version>
    <type>test-jar</type>
    <scope>test</scope>
</dependency>
  • Note the specification of “test-jar” as the <type> instead of “jar”. This will cause the dependency to be on the test jar artifact for the project, which would have been generated with the naming convention:
    <artifactId>-<version>-tests.jar

    Thus, for the dependency define above, the artifact for the dependency would be named “my-artifact-id-1.2-tests.jar”.

  • Note also that you will almost certainly want to specify that the scope for this dependency is “test”, as we did above.

It's only fair to share...
Share on FacebookGoogle+Tweet about this on TwitterShare on LinkedIn

Leave a Reply