單元測試是保障軟體品質的基石。JUnit 作為 Java 領域事實標準,支援測試類/方法層級驗證,並可將多個 TestCase 組合成 TestSuite 實現自動化回歸。Eclipse 內建 JUnit 整合,讓撰寫與執行測試如同開發主代碼般順暢。
Hello.abs() 建立測試package example;
public class Hello {
public int abs(int n) {
return n >= 0 ? n : -n;
}
}

Hello.java → New → JUnit Test Case。junit.jar 至 Build Path,確認後產生 HelloTest。
setUp()、tearDown() 並選擇測試 abs(int) 方法。
public class HelloTest extends TestCase {
private Hello hello;
protected void setUp() { hello = new Hello(); }
protected void tearDown() { hello = null; }
public void testAbs() {
assertEquals(5, hello.abs(5)); // 正數
assertEquals(5, hello.abs(-5)); // 負數
assertEquals(0, hello.abs(0)); // 零
}
}

try {
HelloTest test = new HelloTest();
test.setUp(); // 初始化測試環境
test.testAbs(); // 執行測試方法
test.tearDown(); // 清理資源
} catch (Exception e) { /* 標記失敗 */ }
testXxx() 獨立執行,setUp/tearDown 在每次前後調用,確保隔離性。testA 依賴 testB 的狀態。

public class AllTests {
public static Test suite() {
TestSuite suite = new TestSuite();
suite.addTestSuite(HelloTest.class);
suite.addTestSuite(OtherTest.class);
return suite;
}
}
執行 AllTests 即可一次跑完所有測試,極適合極限編程(XP)每日多次整合測試,防止代碼「腐爛」。
Eclipse + JUnit 讓單元測試零門檻接入開發流程。養成「先寫測試、再寫實作」的習慣(TDD),配合持續整合自動化跑測,能顯著提升專案可維護性與交付信心。