JUnit 4 和 JUnit 5 是完全不同的框架。它们都用于相同的目的,但JUnit 5是一个完全从头编写的测试框架,不使用任何JUnit 4 API的内容。在这里,我们将看如何在我们的Maven项目中设置JUnit 4 和 JUnit 5。
JUnit Maven 依赖
如果您想使用 JUnit 4,那么您只需要以下单一依赖。
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
JUnit 5 分为几个模块,您至少需要 JUnit Platform 和 JUnit Jupiter 来编写 JUnit 5 的测试。另外,请注意 JUnit 5 需要 Java 8 或更高版本。
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.2.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>1.2.0</version>
<scope>test</scope>
</dependency>
如果您想运行 参数化测试,则需要添加额外的依赖。
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>5.2.0</version>
<scope>test</scope>
</dependency>
Maven 构建期间的 JUnit 测试
如果您希望在 Maven 构建期间执行测试,则必须在您的 pom.xml 文件中配置 maven-surefire-plugin
插件。JUnit 4:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.0</version>
<dependencies>
<dependency>
<groupId>org.apache.maven.surefire</groupId>
<artifactId>surefire-junit4</artifactId>
<version>2.22.0</version>
</dependency>
</dependencies>
<configuration>
<includes>
<include>**/*.java</include>
</includes>
</configuration>
</plugin>
</plugins>
</build>
JUnit 5:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.0</version>
<dependencies>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-surefire-provider</artifactId>
<version>1.2.0</version>
</dependency>
</dependencies>
<configuration>
<additionalClasspathElements>
<additionalClasspathElement>src/test/java/</additionalClasspathElement>
</additionalClasspathElements>
</configuration>
</plugin>
</plugins>
</build>
JUnit HTML 報告
Maven surefire 插件生成文本和 XML 報告,我們可以使用 maven-surefire-report-plugin
生成基於 HTML 的報告。下面的配置適用於 JUnit 4 和 JUnit 5。
<reporting>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-report-plugin</artifactId>
<version>2.22.0</version>
</plugin>
</plugins>
</reporting>
只需運行 mvn site
命令,HTML 報告將生成在 target/site/
目錄中。這就是 maven 專案中 JUnit 設置的快速概述。
Source:
https://www.digitalocean.com/community/tutorials/junit-setup-maven