claude-code/claude-zh/commands/test-coverage.md

70 lines
2.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 測試覆蓋率 (Test Coverage)
分析測試覆蓋率,識別缺口,並生成缺失的測試,以達到 80% 以上的覆蓋率。
## 步驟 1偵測測試框架
| 指標 | 覆蓋率指令 |
|-----------|-----------------|
| `jest.config.*``package.json` 中的 jest | `npx jest --coverage --coverageReporters=json-summary` |
| `vitest.config.*` | `npx vitest run --coverage` |
| `pytest.ini` / `pyproject.toml` 中的 pytest | `pytest --cov=src --cov-report=json` |
| `Cargo.toml` | `cargo llvm-cov --json` |
| `pom.xml` 搭配 JaCoCo | `mvn test jacoco:report` |
| `go.mod` | `go test -coverprofile=coverage.out ./...` |
## 步驟 2分析覆蓋率報告
1. 執行覆蓋率指令並擷取輸出
2. 解析輸出結果 (JSON 摘要或終端機輸出)
3. 列出**覆蓋率低於 80%** 的檔案,按覆蓋率由低到高排序
4. 針對每個覆蓋率不足的檔案,識別:
- 未經測試的函式或方法
- 缺失的分支覆蓋 (if/else, switch, 錯誤路徑)
- 膨脹分母的死碼 (Dead code)
## 步驟 3生成缺失的測試
針對每個覆蓋率不足的檔案,按以下優先順序生成測試:
1. **快樂路徑 (Happy path)** — 使用有效輸入測試核心功能
2. **錯誤處理 (Error handling)** — 無效輸入、缺少資料、網路故障
3. **邊緣情況 (Edge cases)** — 空陣列、null/undefined、邊界值 (0, -1, MAX_INT)
4. **分支覆蓋 (Branch coverage)** — 涵蓋每個 if/else, switch case, 三元運算子
### 測試生成規則
- 測試檔案應鄰近原始碼:`foo.ts` → `foo.test.ts` (或遵循專案慣例)
- 使用專案現有的測試模式 (匯入風格、斷言庫、Mock 方式)
- Mock 部依賴 (資料庫、API、檔案系統)
- 每個測試應相互獨立 — 測試之間不共享可變狀態
- 描述性的測試命名:`test_create_user_with_duplicate_email_returns_409`
## 步驟 4驗證
1. 執行完整的測試套件 — 所有測試必須通過
2. 重新執行覆蓋率檢查 — 驗證改善情況
3. 如果仍低於 80%,針對剩餘缺口重覆步驟 3
## 步驟 5報告
顯示前後對比:
```
覆蓋率報告 (Coverage Report)
──────────────────────────────
檔案 之前 之後
src/services/auth.ts 45% 88%
src/utils/validation.ts 32% 82%
──────────────────────────────
總體覆蓋率: 67% 84% ✅
```
## 重點關注區域
- 具有複雜分支的函式 (高循環複雜度)
- 錯誤處理器與 catch 區塊
- 程式碼庫中通用的工具函式 (Utility functions)
- API 端點處理程序 (Request → Response 流程)
- 邊緣情況null, undefined, 空字串, 空陣列, 零, 負數