JUnit 是 Java 單元測試事實標準,Eclipse 內建整合讓測試撰寫與執行極為便利。本文以 Hello.abs() 為例,示範建立測試類別、編寫測試方法、執行與結果解讀、TestSuite 組合自動化的完整流程。
junit.jar,確認example.Hello)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(); // 每個 testXxx() 獨立執行
test.tearDown();
} catch (Exception e) { /* 標記失敗 */ }
testXxx() 獨立建立實例,互不干擾setUp()/tearDown() 在每個測試方法前後執行AssertionFailedError,不捕獲會標紅public class AllTests {
public static Test suite() {
TestSuite suite = new TestSuite();
suite.addTestSuite(HelloTest.class);
suite.addTestSuite(OtherTest.class);
return suite;
}
}
執行 AllTests 即可一次跑完所有測試,適合 XP 持續整合:每次微調程式碼即跑全套,確保不破壞既有功能。
test[MethodName]_[Condition]_[Expected],如 testAbs_NegativeInput_ReturnsPositive「測試是為了發現錯誤而執行程式。」將 JUnit 融入日常開發節奏,能大幅降低回歸風險,提升重構信心。