在另一个maven项目中使用测试类

时间:2014-07-26 20:57:21

标签: java maven testing

我的情况就像照片一样。 enter image description here

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。 那么我可以在另一个项目中使用测试中的类吗?

1 个答案:

答案 0 :(得分:2)

要在 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-xyjar ,而且Maven还将创建另一个工件: ProjA-xy-tests。 jar ,其中包含所有类的ProjA测试代码。

2.现在你需要在 ProjB / pom.xml 中添加对 ProjA-xy-tests.jar 工件的依赖(除了已经存在的依赖项)到 ProjA-xyjar ):

<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测试类都可用。

相关问题