1. 介绍 JUnit
JUnit 是 Java 语言中最流行的单元测试框架之一。它基于 xUnit 设计模式,支持 测试自动化、断言(Assertions)和测试生命周期管理,是 Java 开发中进行 TDD(测试驱动开发) 的重要工具。
JUnit 主要特点:
- 轻量级:不需要复杂的配置即可使用。
- 自动化测试:支持
@Test
注解实现测试自动化。 - 测试报告:与 Maven、Gradle 和 CI/CD 集成,生成测试报告。
- 参数化测试:支持
@ParameterizedTest
进行数据驱动测试。 - 兼容性:JUnit 5 兼容 JUnit 4/3,并提供
Vintage
组件用于向后兼容。
2. 安装 JUnit(Maven 项目)
在 pom.xml
中添加 JUnit 5 依赖(推荐使用 junit-jupiter
聚合依赖):
<properties><junit.version>5.9.2</junit.version>
</properties><dependencies><dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter</artifactId><version>${junit.version}</version><scope>test</scope></dependency>
</dependencies>
完整版本的 pom.xml
配置:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>org.example</groupId><artifactId>MyTestJava</artifactId><version>1.0-SNAPSHOT</version><properties><maven.compiler.source>17</maven.compiler.source><maven.compiler.target>17</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><junit.version>5.9.2</junit.version> <!-- 定义 JUnit 版本变量 --></properties><dependencies><dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter</artifactId><version>${junit.version}</version><scope>test</scope></dependency></dependencies></project>
然后刷新 Maven 依赖:
mvn clean install
也可以通过下面的方式刷新依赖:
3. 编写 JUnit 测试代码
创建 APITest.java
并添加以下代码:
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;public class APITest {int add(int a, int b) {return a + b;}@Testvoid testAddition() {assertEquals(5, add(2, 3));assertEquals(-1, add(-2, 1));}
}
解释:
@Test
:标记为 JUnit 测试方法。assertEquals(expected, actual)
:断言expected
与actual
结果是否相等。
4. 运行 JUnit 测试
方法 1:使用 IntelliJ IDEA 运行
- 右键
APITest.java
,选择Run 'APITest'
。 - 在 测试窗口 查看测试结果。
方法 2:使用 Maven 运行
在 IDEA 的 Terminal 运行:
mvn test
方法 3:在 CI/CD(如 GitHub Actions)中运行
- name: Run Testsrun: mvn test
5. JUnit 进阶功能
5.1 断言(Assertions)
JUnit 提供多种断言方式:
@Test
void testAssertions() {assertTrue(3 > 2, "3 应该大于 2");assertFalse(2 > 3, "2 不应该大于 3");assertNull(null);assertNotNull("Hello");assertThrows(ArithmeticException.class, () -> { int x = 1 / 0; });
}
5.2 测试生命周期(Setup & Teardown)
JUnit 5 提供 @BeforeEach
和 @AfterEach
进行 测试前后初始化和清理:
import org.junit.jupiter.api.*;class TestLifecycle {@BeforeEachvoid setUp() {System.out.println("测试开始");}@Testvoid testSomething() {System.out.println("执行测试");}@AfterEachvoid tearDown() {System.out.println("测试结束");}
}
5.3 参数化测试
使用 @ParameterizedTest
进行 数据驱动测试:
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;class ParameterizedExample {@ParameterizedTest@ValueSource(strings = {"JUnit", "TestNG", "Mockito"})void testWithParameters(String framework) {assertNotNull(framework);}
}
6. 解决 JUnit 运行时报错问题
junitjupiterapi_194">问题 1:ClassNotFoundException: org.junit.jupiter.api
原因:JUnit 依赖未正确解析。
解决方案:
- 检查
pom.xml
,确保junit-jupiter
依赖存在。 - 刷新 Maven 依赖(右键
pom.xml
→Reload Project
)。
junitjupiter_failed_to_discover_tests_201">问题 2:TestEngine with ID ‘junit-jupiter’ failed to discover tests
原因:缺少 junit-jupiter-engine
。
解决方案:
问题 3:Maven 运行 mvn test
时报错
解决方案:
mvn clean test -U # 强制更新依赖
7. 总结
步骤 | 操作 |
---|---|
安装 JUnit | pom.xml 添加 junit-jupiter 依赖 |
编写测试代码 | 使用 @Test 方法进行断言 |
运行测试 | IDEA 运行,或 mvn test |
高级功能 | 断言、生命周期、参数化测试 |
使用 JUnit 5 + IntelliJ IDEA,可以轻松进行 Java 单元测试,提高代码质量,并支持自动化测试!