【问题标题】:JUnit categories with multi module project - Unable to load category具有多模块项目的 JUnit 类别 - 无法加载类别
【发布时间】:2017-10-10 21:01:18
【问题描述】:

我想包含/排除 JUnit 分类测试。我在公共模块中定义了一个标记接口StressTest。我在 moduleA 中引用 StressTest。我在 root pom.xml 中有以下 maven-surefire-plugin

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

运行 mvn test 时,我在构建另一个模块时得到以下信息。

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

我应该在哪里写我的StressTest 接口?

【问题讨论】:

    标签: java maven unit-testing testing junit4


    【解决方案1】:

    为了确保“找到”您的 @Category 类,它必须位于从您的 Maven 项目的依赖树生成的类路径中。

    这个例外...

    无法加载类别:com.mycompany.project.common.utils.StressTest

    ...强烈暗示包含com.mycompany.project.common.utils.StressTest 的任何工件不是您的moduleA 的声明依赖项。

    因此,您需要将对包含 com.mycompany.project.common.utils.StressTest 的任何工件的依赖项添加到您的 moduleA。如果此依赖项的唯一目的是提供 @Category 类,那么将这个依赖项测试限定为范围是有意义的,例如

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

    此外,如果com.mycompany.project.common.utils.StressTest 位于 test 树而不是 common utils 模块中的 ma​​in 树中,那么您将需要创建一个包含 common utils 的 JAR模块的测试类。您可以通过将以下 maven-jar-plugin 声明添加到常用 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>
    

    然后,您将在 moduleA 的依赖项中使用 &lt;type&gt;test-jar&lt;/type&gt; 来依赖它,例如:

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

    【讨论】:

    • 如果我在 test/java 下定义了StressTest,那么它就不起作用,但如果我在 main/java 中定义它,它就会起作用。
    • @bluetech 我已经更新了答案,以描述如何从您的常用 utils 模块中导出和依赖 test-jar
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-02
    • 1970-01-01
    • 2021-12-15
    • 2015-09-21
    • 2023-04-10
    • 1970-01-01
    相关资源
    最近更新 更多