reusing unit tests in maven2

Maven2 has a nice mechanism to reuse junit code across modules. All it requires is that you put following plugin configuration in the build/plugins section of your pom:


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

Now the avid maven2 user will at this point note that this is already nicely covered by one of the maven2 guides. Very true. So why write about it ?

Well it turns out that there is a slight catch when you actually try to put the artifact produced by above configuration as a dependency in your jar. Let me explain with an example:

1. Let’s assume your artifact is called cocoon-core, version 1.0. Above configuration will thus produce an artifact called cocoon-core-1.0.jar and cocoon-core-1.0-tests.jar. Let’s also assume this artifact has a dependency on eg daisy-htmlcleaner with scope test, expressed as:

<dependency>
<groupId>org.outerj.daisy</groupId>
<artifactId>daisy-htmlcleaner</artifactId>
<version>1.4.1</version>
<scope>test</scope>
</dependency>

2. Let’s assume that in another module, that happens to use cocoon-core already (the actual code, not the unit tests) i would like to start reusing the unit tests, so i should be able to just use

<!– adding the dependency on the test jar –>
<dependency>
<groupId>org.apache.cocoon</groupId>
<artifactId>cocoon-core</artifactId>
<version>1.0</version>
<classifier>tests</classifier>
<scope>test</scope>
</dependency>
<!– we had this dependency already –>
<dependency>
<groupId>org.apache.cocoon</groupId>
<artifactId>cocoon-core</artifactId>
<version>1.0</version>
</dependency>

… right ?

Nope. A bug in maven2 transitive dependency resolution causes it to remove the transitive dependencies with test scope from dependency calculation.

The trick here is simply to redefine these dependencies, and remove them when this bug is solved - just like i did here.

By the way, my name is Jorg Heymans, in case you hadn’t noticed already :-) . Welcome to my blog.