Tuesday, 14 January 2014

Java - re-using test classes across different projects | modules | packages

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

In the POM.xml of the project|module that you have your testing code in src/test/java, include this plugin:
<project>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <version>2.2</version>
        <executions>
          <execution>
            <goals>
              <goal>test-jar</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>

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. E.g:
[your project|module name]/src/main/
[your project|module name]/src/test/


In the other project|module POM.xml, include this dependency:
<dependency>
  <groupId>com.rookiegeek.foobar</groupId>
  <artifactId>foo-bar</artifactId>
  <version>1.0.0</version>
  <type>test-jar</type>
  <scope>test</scope>
</dependency>

The 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.