单元测试框架集成
Maven 通过 surefire 插件集成 JUnit/TestNG 测试框架。
JUnit 4 集成
依赖配置
XML
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
surefire 配置
XML
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
JUnit 5 集成
依赖配置
XML
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.8.2</version>
<scope>test</scope>
</dependency>
surefire 配置(需要 2.22.0+)
XML
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
TestNG 集成
依赖配置
XML
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.5</version>
<scope>test</scope>
</dependency>
surefire 配置
XML
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>testng.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
测试类命名约定
默认匹配模式
| 模式 | 说明 |
|---|---|
| **/*Test.java | 结尾为 Test |
| **/*Tests.java | 结尾为 Tests |
| **/*TestCase.java | 结尾为 TestCase |
执行测试
基本命令
Bash
mvn test
指定测试类
Bash
mvn test -Dtest=UserServiceTest
要点总结
- JUnit 4:junit:junit + surefire 2.x
- JUnit 5:junit-jupiter + surefire 2.22+
- TestNG:testng:testng + suiteXmlFiles
- 默认匹配 *Test.java、*Tests.java
- mvn test 执行单元测试
📝 发现内容有误?点击此处直接编辑