【问题标题】:Using test class in another maven project在另一个 Maven 项目中使用测试类
【发布时间】:2014-07-26 20:57:20
【问题描述】:

我遇到了如图所示的情况。

ProjB 依赖于 ProjA。 在 src/test/java 的 ProjA 中,我有一些 Util 类用于测试目的。我也想在 ProjB 的测试中使用这个 Util。

public class TestB {    
  @Test
  public void sth(){
    Util u = new Util();
  }
}

public class Util {
  public void util(){
      System.out.println("do something");
  }
}

ProjA/pom.xml 依赖于 junit 4.11, ProjB/pom.xml 对 ProjA 有依赖。

当我运行 TestB 时,出现 java.lang.ClassNotFoundException: aaaa.Util 异常。 那么我可以在另一个项目中使用测试中的类吗?

【问题讨论】:

标签: java maven testing


【解决方案1】:

要在ProjB中使用ProjA的测试代码,你需要做两件事:

1.) 将以下行添加到 ProjA/pom.xml<build> 部分:

<pluginManagement>
    <plugins>
        <plugin>
            <artifactId>maven-jar-plugin</artifactId>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>test-jar</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</pluginManagement>

通过这个添加,您不仅会在执行mvn package 时获得工件ProjA-x.y.jar,而且Maven 还会创建另一个工件:ProjA-x.y-tests.jar 其中包含 ProjA 测试代码的所有类。

2.) 现在您需要向您的 ProjB/pom.xml 中添加对这个 ProjA-x.y-tests.jar 工件的依赖项(除了已经存在的依赖项到ProjA-x.y.jar):

<dependencies>
    <!-- the dependency to the production classes of ProjA ... -->
    <dependency>
        <groupId>foo</groupId>
        <artifactId>ProjA</artifactId>
        <version>x.y</version>
    <dependency>
    <!-- the dependency to the test classes of ProjA ... -->
    <dependency>
        <groupId>foo</groupId>
        <artifactId>ProjA</artifactId>
        <classifier>tests</classifier>
        <version>x.y</version>
        <scope>test</scope>
    <dependency>
</dependencies>

现在在测试 ProjB 时,ProjA 的所有测试类都可以在类路径中使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-25
    • 1970-01-01
    • 2020-12-14
    • 2015-11-18
    • 1970-01-01
    • 1970-01-01
    • 2012-09-08
    • 2020-04-26
    相关资源
    最近更新 更多