Maven: use specific test-classes of project A in project B

4.4k Views Asked by At

I have projects A and B where B requires A. Inside project A I have a utility-class UC that should only be available for JUnit-tests and, therefore, resides in src/test/java of project A. As long as I write tests in A I have access to UC. However, if I run Maven and want it to execute the tests in B, I get compiler errors since UC is not accessible in B.

Obviously Eclipse includes all classes in all source folders when it compiles something (i.e., it knows about UC when I write tests in B), while Maven removes all test-classes in the final version of A.

My question is this: what do I need to do to have UC accessible in B when I run its tests with Maven?

Please understand that I'm new to Maven and I think that similar questions have been asked. However, I can't convert what is written there into my problem and fix it.

I hope it's clear what I'm trying to do...

3

There are 3 best solutions below

0
On BEST ANSWER

After looking some more I finally found a solution:

http://www.waltercedric.com/java-j2ee-mainmenu-53/361-maven-build-system/1349-maven-reusing-test-classes-across-multi-modules-projects.html 1

I've seen this pattern occasionally on other questions, so I guess I just didn't understand it that way... Oh, well. *eyeroll*

1 That original link stopped working. I found it again on archive.org (don't mind the awkward layout).

0
On

I have always found test-jars awkward. They're kind of peculiar, because they only get used once freshly deployed to the repository. Otherwise other projects do not see the changes. This is why I recommend creating just normal projects which you can use to put your test helpers into and then refer to them by using a test scope dependency.

4
On

The maven-jar-plugin page - http://maven.apache.org/plugins/maven-jar-plugin/usage.html - mentions two ways. The simple approach is creating a test-jar artifact, and then refer to that. (snippets blatantly copied from official page)

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

and then refer to it with the test-jar type and test scope in the projects that need it:

<project>
  ...
  <dependencies>
    <dependency>
      <groupId>groupId</groupId>
      <artifactId>artifactId</artifactId>
      <type>test-jar</type>
      <version>version</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  ...
</project>

If you need to do this a lot you should most likely consider moving your test code to separate projects.