标识 Java Maven 项目中的测试目录



我在项目中没有遵循一般的Maven项目结构。这就是我的项目结构的样子 -

ProjectName
 |- src
    |- app
       |- models
       |- services
    |- test
       |- unit
          |- services
       |- integration
          |- services

对于测试,我使用的是JunitMockito。我的pom.xml文件看起来像这样 -

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>ProjectName</groupId>
  <artifactId>ProjectName</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <dependencies>
    <!-- https://mvnrepository.com/artifact/junit/junit -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.mockito/mockito-all -->
    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-all</artifactId>
      <version>1.10.19</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <resources>
      <resource>
        <directory>src</directory>
        <excludes>
          <exclude>**/*.java</exclude>
        </excludes>
      </resource>
    </resources>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.5.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

我现在面临的问题是,当我运行测试时,它无法找到依赖包 junit 和 mockito。我知道这是因为我已经将这些依赖项的范围声明为测试

想知道的是,我应该在我的pom.xml文件中进行什么更改,以便Maven可以识别我的测试目录?

Maven surefire 插件将在属性 project.build.testSourceDirectory 指向的目录中查找测试。

因此,您可以将其添加到您的pom中.xml以更改此属性的值:

<build>
    <testSourceDirectory>${project.basedir}/src/test</testSourceDirectory>
</build>

这将在测试阶段执行所有测试(单元和集成)。如果不想执行集成测试,可以将该属性设置为 ${project.basedir}/src/test/unit

我还建议像其他人一样遵循 maven 项目的约定。

尽管如此,事情应该通过覆盖以下 maven 属性来工作,如下所示:

<properties>
  <!-- Considering src/app will have all your sourcr java code -->
  <project.build.sourceDirectory>src/app</project.build.sourceDirectory>
  <!-- Considering all your junit tests are in src/test/unit -->
  <project.build.testSourceDirectory>src/test/unit</project.build.testSourceDirectory>
  ...
</properties>

如果您想使用 maven 添加集成测试,那么我建议您阅读本文。

您可以从<build>部分中删除<sourceDirectory><resources>

最新更新