Search code examples
javamavenunit-testingtestingjunit4

JUnit categories with multi module project - Unable to load category


I want to include/exclude JUnit categorized tests. I have a marker interface StressTest defined in a common module. I am referencing StressTest in moduleA. I have the following maven-surefire-plugin in root pom.xml

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.20</version>
<configuration>
  <excludedGroups>com.mycompany.project.common.utils.StressTest</excludedGroups>
</configuration>
</plugin>

When running mvn test I get the following while building another module.

Unable to load category: com.mycompany.project.common.utils.StressTest

Where should I write my StressTest interface?


Solution

  • In order for surefire to 'find' your @Category class it must be on the classpath produced from your Maven project's dependency tree.

    This exception ...

    Unable to load category: com.mycompany.project.common.utils.StressTest

    ... strongly implies that whatever artifact contains com.mycompany.project.common.utils.StressTest is not a declared dependency of your moduleA.

    So, you'll need to add a dependency on whatever artifact contains com.mycompany.project.common.utils.StressTest to your moduleA. If the only purpose of this dependency is to provide the @Category class then it would make sense to make this dependency test scoped e.g.

    <dependency>
        <groupId>com.mycompany</groupId>
        <artifactId>common.utils</artifactId>
        <version>...</version>
        <scope>test</scope>
    </dependency>
    

    Furthermore, if com.mycompany.project.common.utils.StressTest is in the test tree rather than the main tree in your common utils module then you will need to create a JAR containing the common utils module's test classes. You can do this by adding the following maven-jar-plugin declaration to the common utils' pom.xml:

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

    You would then depend on this using <type>test-jar</type>in the dependency in your moduleA, for example:

    <dependency>
        <groupId>com.mycompany</groupId>
        <artifactId>common.utils</artifactId>
        <version>...</version>
        <type>test-jar</type>
        <scope>test</scope>
    </dependency>