全部学科
Python全栈
python
NodeJS全栈
nodejs
📅 2026-05-23 8 分钟 ✍️ juanwangdev

单元测试框架集成

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 执行单元测试
想在手机上练习这篇文章的配套题目?
使用微信卷王开发者小程序,打开首页顶部扫码功能识别二维码
← 上一篇 Profile 外部化配置管理
下一篇 → 测试覆盖率统计
扫码体验小程序
加载中
想在手机上刷题学习?
使用微信卷王开发者小程序,打开首页顶部扫码功能识别二维码