首页/ 学科题库/ maven/ 单元测试框架集成
maven 实战教程

单元测试框架集成

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 执行单元测试
想在手机上练这篇的配套题目?
使用微信 卷王开发者小程序/App,首页顶部扫一扫识别下方二维码,即可解锁本讲对应真题与错题本。
了解产品 App
← 上一篇 Profile 外部化配置管理 下一篇 → 测试覆盖率统计