全部学科
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 执行单元测试

📝 发现内容有误?点击此处直接编辑

← 上一篇 环境差异化配置
下一篇 → 测试并行与性能优化
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库