為示範單元測試全流程,選取兩個具代表性的工具類:
Subsectionpublic class Subsection {
/** 符號函數:負數→-1,零→0,正數→1 */
getValue(int d) 邏輯:
d < -2 → |d|-2 ≤ d < 2 且 d ≠ 0 → d²d = 0 → 100d ≥ 2 → d³(註:d > 32 時 d³ 溢位 int,原始碼刻意註解溢位保護,模擬潛在 Bug)StringUtils核心方法:string2Array(String str, char splitChar, boolean trim)
trim() 去首尾分隔符、getCharCount() 計算分隔符數量決定陣列大小null 輸入返回 null、空字串、連續分隔符、首尾分隔符| 輸入 d | 預期輸出 | 測試焦點 |
|---|---|---|
| -5 | 5 | d < -2,絕對值 |
| -2 | 4 | 邊界 -2,平方 |
| -1 | 1 | 區間內負數平方 |
| 0 | 100 | 特殊值 0 |
| 1 | 1 | 區間內正數平方 |
| 2 | 8 | 邊界 2,立方 |
| 33 | 溢位/異常 | d > 32 溢位測試(預期失敗,驗證 Bug 存在) |
| 輸入字串 | 分隔符 | trim | 預期結果 | 測試焦點 |
|---|---|---|---|---|
| "a,b,c" | ',' | false | ["a","b","c"] | 基本分割 |
| ",a,b,c," | ',' | true | ["a","b","c"] | 首尾分隔符去除 |
| ",,a,,b,," | ',' | true | ["","a","","b",""] | 連續分隔符產生空元素 |
| null | ',' | true | null | 空輸入保護 |
| "" | ',' | false | [""] | 空字串語義 |
assertEquals、assertArrayEquals、assertNull)Ctrl+F10public class SubsectionTest extends TestCase {
public void testGetValue_BoundaryNegativeTwo() {
assertEquals(4, Subsection.getValue(-2));
}
public void testGetValue_Zero() {
assertEquals(100, Subsection.getValue(0));
}
public void testGetValue_Overflow() {
// 預期失敗:33^3 = 35937 > Integer.MAX_VALUE? 實際 33^3=35937 未溢位,需更大值
// 修正:Integer.MAX_VALUE=2147483647, 1290^3≈2.14e9 接近溢位
assertEquals(35937, Subsection.getValue(33)); // 此處通過,溢位測試需調整輸入
}
}
public class StringUtilsTest extends TestCase {
public void testString2Array_Trim() {
String[] expected = {"a", "b", "c"};
assertArrayEquals(expected, StringUtils.string2Array(",a,b,c,", ',', true));
}
public void testString2Array_NullInput() {
assertNull(StringUtils.string2Array(null, ',', true));
}
}
splitChar 為字串的多字元分割需求)@Parameterized (JUnit 4+) 或資料驅動測試框架以 Subsection 與 StringUtils 為例,展示了從需求分析 → 測試矩陣設計 → JBuilder 生成骨架 → 補全斷言 → 執行驗證 → 重構補強的完整單元測試閉環。測試不僅是「驗證正確」,更是活文檔、重構安全網、設計質量檢驗器。掌握邊界值、等價類、異常路徑三大測試技法,配合 IDE 自動化支援,讓測試真正融入日常開發節奏。