JUnit 4 和 JUnit 5 是完全不同的框架,它们都服务于相同的目的,但 JUnit 5 是从头开始写的完全不同的测试框架,它不使用任何 JUnit 4 API. 在这里,我们将研究如何在我们的 maven 项目中设置 JUnit 4 和 JUnit 5。
依赖性 Maven
如果你想使用 JUnit 4,那么你需要一个单一的依赖,如下。
1<dependency>
2 <groupId>junit</groupId>
3 <artifactId>junit</artifactId>
4 <version>4.12</version>
5 <scope>test</scope>
6</dependency>
JUnit 5 被分成几个模块,你至少需要 JUnit Platform和 JUnit Jupiter来编写 JUnit 5 中的测试。
1<dependency>
2 <groupId>org.junit.jupiter</groupId>
3 <artifactId>junit-jupiter-engine</artifactId>
4 <version>5.2.0</version>
5 <scope>test</scope>
6</dependency>
7<dependency>
8 <groupId>org.junit.platform</groupId>
9 <artifactId>junit-platform-runner</artifactId>
10 <version>1.2.0</version>
11 <scope>test</scope>
12</dependency>
如果你想运行 [参数化测试]( / 社区 / 教程 / 参数化测试),那么你需要添加一个额外的依赖性。
1<dependency>
2 <groupId>org.junit.jupiter</groupId>
3 <artifactId>junit-jupiter-params</artifactId>
4 <version>5.2.0</version>
5 <scope>test</scope>
6</dependency>
在 Maven Build 期间进行 JUnit 测试
如果您希望在 maven 构建过程中执行测试,则必须在 pom.xml 文件中配置 maven-surefire-plugin
插件。
1<build>
2 <plugins>
3 <plugin>
4 <groupId>org.apache.maven.plugins</groupId>
5 <artifactId>maven-surefire-plugin</artifactId>
6 <version>2.22.0</version>
7 <dependencies>
8 <dependency>
9 <groupId>org.apache.maven.surefire</groupId>
10 <artifactId>surefire-junit4</artifactId>
11 <version>2.22.0</version>
12 </dependency>
13 </dependencies>
14 <configuration>
15 <includes>
16 <include>**/*.java</include>
17 </includes>
18 </configuration>
19 </plugin>
20 </plugins>
21</build>
第五章 :
1<build>
2 <plugins>
3 <plugin>
4 <groupId>org.apache.maven.plugins</groupId>
5 <artifactId>maven-surefire-plugin</artifactId>
6 <version>2.22.0</version>
7 <dependencies>
8 <dependency>
9 <groupId>org.junit.platform</groupId>
10 <artifactId>junit-platform-surefire-provider</artifactId>
11 <version>1.2.0</version>
12 </dependency>
13 </dependencies>
14 <configuration>
15 <additionalClasspathElements>
16 <additionalClasspathElement>src/test/java/</additionalClasspathElement>
17 </additionalClasspathElements>
18 </configuration>
19 </plugin>
20 </plugins>
21</build>
HTML 报告
Maven surefire 插件生成文本和 XML 报告,我们可以使用maven-surefire-report-plugin
生成基于 HTML 的报告。
1<reporting>
2 <plugins>
3 <plugin>
4 <groupId>org.apache.maven.plugins</groupId>
5 <artifactId>maven-surefire-report-plugin</artifactId>
6 <version>2.22.0</version>
7 </plugin>
8 </plugins>
9</reporting>
只需运行mvn site
命令,在target/site/
目录中将生成HTML报告。