← ClaudeAtlas

legacy-code-characterizationlisted

Write characterization tests for untested legacy code to lock current behavior before refactoring. Use when users want to safely refactor legacy controllers/models/services, add regression safety nets, or prepare code for extraction. Trigger words: characterization test, lock behavior, legacy test, safe refactor, 行為鎖定, 特徵測試, 安全重構. Not for: greenfield code, already well-tested modules, or pure bug fixes. Output: characterization test files + coverage delta report.
hmj1026/dhpk · ★ 1 · Data & Documents · score 72
Install: claude install-skill hmj1026/dhpk
# Legacy Code Characterization Skill ## 概述 針對無測試或低測試覆蓋率的 legacy code,撰寫 characterization tests(特徵測試)以鎖定現有行為,為後續重構提供安全網。 此技術來自 Michael Feathers 的《Working Effectively with Legacy Code》。核心思想: **先觀察程式實際在做什麼,把觀察到的輸出寫成 assertion,讓它通過(GREEN),再開始重構。** ## When to Use - 準備重構超過 300 行的 legacy class / controller - 需要為關鍵業務邏輯建立回歸測試,但無法修改現有結構 - 測試覆蓋率提升計畫中的 legacy 模組 - 提取 Service / Repository 前的行為快照 ## When NOT to Use - 新功能開發(用 TDD 流程) - 已有充分測試的模組 - 純 bug fix 且根因明確 --- ## Characterization Test 生命週期 Characterization tests 不是永久存在的,有明確三段生命週期: 1. **鎖定(Lock)**:寫 characterization test,執行確認 GREEN → 行為已鎖定 2. **重構(Refactor)**:安全重構目標程式碼,測試持續 GREEN 代表行為不變 3. **提取(Extract)**:重構完成後,抽出 pure unit test 承接輸出契約;characterization test 可退役或保留為回歸 > 典型路徑:`LegacyClassCharacterizationTest`(鎖定原始行為)→ 抽出 `XxxNormalizer` → `XxxNormalizerTest`(pure unit 承接)→ characterization test 退役 --- ## 工作流程 ### Phase 1: 行為盤點 1. 閱讀目標檔案,列出所有公開方法 2. 識別外部依賴(DB query、外部 API、全域 state、singleton) 3. 標記高風險方法(涉及金額、付款、庫存、資料寫入) 4. 確認既有測試覆蓋狀況 5. 產出方法清單 + 依賴清單 ``` 格式: | 方法 | 行數 | 依賴 | 風險等級 | 現有測試 | |------|------|------|---------|---------| | actionCheckout | 45-120 | DB, PaymentAPI | HIGH | 無 | | calcDiscount | 30-55 | 無 | LOW | 無 | ``` **大型 class(trait-heavy / 數千行)注意事項:** - 不嘗試整體覆蓋;以**高風險方法優先** - 多 trait 混入時,明確標記測試覆蓋的是哪個 trait 的行為 - 優先選擇**邊界清楚的 public methods**,避免深度依賴 HTTP 或 global state ### Phase 2: 測試策略選擇 根據依賴類型選擇測試層級: | 依賴類型 | 建議層級 | 特性 | |---------|---------|------| | 純計算(無外部依賴) | Unit test | 最快、最穩定 | | 需