JUnit 推薦以 test 開頭命名測試方法,配合 TestSuite 反射自動發現。以下是最精簡的完整範例:
package junitfaq;
import java.util.*;
import junit.framework.*;
public class SimpleTest extends TestCase {
public SimpleTest(String name) { super(name); }
public void testEmptyCollection() {
Collection collection = new ArrayList();
assertTrue(collection.isEmpty());
}
public static Test suite() {
return new TestSuite(SimpleTest.class);
}
public static void main(String[] args) {
junit.textui.TestRunner.run(suite());
}
}
java junitfaq.SimpleTest
# 輸出:
# .
# Time: 0
# OK (1 tests)
每個 . 代表一個通過的測試;失敗顯示 F,錯誤顯示 E。
java junit.swingui.TestRunner junitfaq.SimpleTest
綠條 = 全部通過,紅條 = 有失敗/錯誤,可點擊查看堆疊軌跡。
protected void setUp() {
// 每個 testXxx 前執行:開啟連線、建立臨時檔案、初始化 Mock 物件等
}
protected void tearDown() {
// 每個 testXxx 後執行:關閉連線、刪除臨時檔案、重置靜態狀態等
}
確保測試之間相互隔離,避免副作用干擾。
assertEquals、assertTrue 等)NullPointerException、ArrayIndexOutOfBoundsException 等)遇到非 OK 結果應立即根據提示修正,保持測試常態綠燈。