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 運行時報錯問題
問題 1:ClassNotFoundException: org.junit.jupiter.api
原因:JUnit 依賴未正確解析。
解決方案:
- 檢查
pom.xml
,確保junit-jupiter
依賴存在。 - 刷新 Maven 依賴(右鍵
pom.xml
→Reload Project
)。
問題 2:TestEngine with ID ‘junit-jupiter’ failed to discover tests
原因:缺少 junit-jupiter-engine
。
解決方案:
- 直接使用
junit-jupiter
聚合依賴,避免單獨引入junit-jupiter-api
。
問題 3:Maven 運行 mvn test
時報錯
解決方案:
mvn clean test -U # 強制更新依賴
7. 總結
步驟 | 操作 |
---|---|
安裝 JUnit | pom.xml 添加 junit-jupiter 依賴 |
編寫測試代碼 | 使用 @Test 方法進行斷言 |
運行測試 | IDEA 運行,或 mvn test |
高級功能 | 斷言、生命周期、參數化測試 |
使用 JUnit 5 + IntelliJ IDEA,可以輕松進行 Java 單元測試,提高代碼質量,并支持自動化測試!