Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should I put test support code for a Java library

I have a Maven project which is used as a library in other projects. The setup is pretty standard: src/main with the library code, src/test with test cases for src/main.

Let's assume I have a project foo which depends in this library. foo also has test cases. To help writing tests in foo for code that uses my library, I'd like to give foo a support framework to write tests (like setting up a mock environment).

Where can I put this support code?

  • It shouldn't go into src/main because it's not meant to go into production.
  • It can't go into src/test because creating a dependency from foo's tests to the tests of the library adds too much junk to the classpath (like logback-test.xml config files, tests which are never executed, ...).

I could put the code into a new module but it's tightly coupled with the code in src/main, so I'd like to keep it in the same project (would also allow the test support code to access package private fields and methods).

Also, the code in src/test should have access to it, so that I can use it to write my own unit tests.

What are my options with Maven to keep this in the same project but still separate it cleanly from both src/main and src/test? Can I somehow create a third output JAR for, say, src/test-support? Or should I put the code into src/test and then use filters in the JAR plugin to include only the support code?

like image 825
Aaron Digulla Avatar asked Dec 21 '12 13:12

Aaron Digulla


1 Answers

You can do this with the Maven Jar Plugin

Maven Jar Plugin

Since you're using Maven you can just cut a separate artifact of the project that contains the libraries you want to use in foo add the following plugin to create another jar artifact:

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

This creates a second jar in this project of everything in the src/test directory.

Test Jars

You could splice out the stuff in that jar you don't need with some filters.

Then to use this library you would include this as a dependancy in foo:

 <dependency>
    <groupId>your.group</groupId>
    <artifactId>parent-artifact-id</artifactId>
    <version>1.0.0</version>
    <type>test-jar</type>
    <scope>test</scope>
 </dependency>

To separate the projects further you can also create a test only project with your more frameworky test jars.
See How to create a jar containing test classes (Preferred way) in the Maven Jar Plugin doc

like image 109
Bob Paulin Avatar answered Nov 02 '22 23:11

Bob Paulin