JUnit 4 是測試框架歷史上最大一次革新,核心目標是利用 Java 5 的 Annotation(註解)特性徹底簡化測試編寫。告別強制繼承 TestCase、方法名必須以 test 開頭的束縛,擁抱更靈活、更語義化的測試風格。
public class AddOperationTest extends TestCase {
public void setUp() throws Exception {}
public void tearDown() throws Exception {}
public void testAdd() {
AddOperation instance = new AddOperation();
assertEquals(0, instance.add(0, 0));
}
}
痛點:必須繼承 TestCase、測試方法強制 test 前綴、靜態導入雖簡化斷言但結構仍顯笨重。
import org.junit.*;
public class AddOperationTest {
@Before
public void setUp() throws Exception {}
@After
public void tearDown() throws Exception {}
@Test
public void add() {
AddOperation instance = new AddOperation();
assertEquals(0, instance.add(0, 0));
}
}
亮點:
@Test 識別測試點。@Before/@After 替代 setUp/tearDown,每個測試方法前後各執行一次。| 註解 | 用途 | 關鍵屬性/行為 |
|---|---|---|
@Test | 標記測試方法 | expected=Exception.class 驗證拋出異常;timeout=毫秒 超時失敗 |
@Before | 每測試方法前執行 | 僅允許一個,替代 setUp() |
@After | 每測試方法後執行 | 僅允許一個,替代 tearDown() |
@Ignore | 暫時禁用測試 | 可附原因:@Ignore("尚未實現"),報告中顯示原因而非失敗 |
@BeforeClass | 類加載前一次性執行 | 方法必須 static,適合昂貴資源初始化(JUnit 4.4+) |
@AfterClass | 所有測試後一次性執行 | 方法必須 static,資源釋放 |
@Test(expected = IllegalArgumentException.class)
public void testInvalidInput() {
calculator.divide(1, 0); // 預期拋出異常
}
@Test(timeout = 100)
public void testPerformance() {
heavyComputation(); // 必須在 100ms 內完成
}
@Ignore("依賴外部數據庫,暫時跳過")
@Test
public void testWithDatabase() { ... }
import static org.junit.Assert.*; 讓 assertEquals、assertTrue 等斷言方法可直接調用,代碼更乾淨。
@Ignore 管理技術債,避免註釋掉測試代碼導致維護失控。JUnit 4 讓測試代碼回歸業務語義,減少框架樣板代碼干擾,是提升測試可讀性與維護性的關鍵一步。