claude-code/claude-zh/skills/springboot-tdd/SKILL.md

56 lines
2.2 KiB
Markdown
Raw Permalink 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.

---
name: springboot-tdd
description: 使用 JUnit 5, Mockito, MockMvc, Testcontainers 與 JaCoCo 進行 Spring Boot 的測試驅動開發 (TDD)。適用於功能開發、臭蟲修復或重構時。
---
# Spring Boot TDD 工作流 (Spring Boot TDD Workflow)
針對 Spring Boot 服務的 TDD 指引,旨在達成 80% 以上的測試覆蓋率(單元測試 + 整合測試)。
## 何時使用
- 開發新功能或 API 端點。
- 修復 Bug 或進行程式碼重構。
- 添加資料存取邏輯 (Data Access) 或安全性規則。
## 標準工作流
1. **先寫測試 (RED)**:撰寫會失敗的測試案例。
2. **實作功能 (GREEN)**:編寫最少量的程式碼使測試通過。
3. **重構優化 (REFACTOR)**:在測試通過的前提下優化程式碼架構。
4. **檢查覆蓋率 (JaCoCo)**:確保關鍵路徑覆蓋完整。
## 測試策略與工具
### 單元測試 (Unit Tests)
- **工具**JUnit 5 + Mockito。
- **模式**Arrange-Act-Assert (AAA)。
- **重點**:使用 `@Mock``@InjectMocks` 隔離外部依賴,專注於 Service 邏輯。
### Web 層測試 (Web Layer Tests)
- **工具**`@WebMvcTest` + `MockMvc`
- **重點**:針對 Controller 進行輕量級測試,驗證 HTTP 狀態碼與 JSON 回應格式(使用 `jsonPath`)。
### 整合測試 (Integration Tests)
- **工具**`@SpringBootTest` + `@AutoConfigureMockMvc`
- **重點**:啟動完整的 Spring 上下文與真實的資料庫進行端到端流量測試。
### 持久層測試 (Persistence Tests)
- **工具**`@DataJpaTest` + Testcontainers。
- **重點**:使用 **Testcontainers** 啟動真實的資料庫鏡像(如 Postgres取代 H2 記憶體資料庫,以模擬真實生產環境。
## 覆蓋率與斷言
- **檢查工具**JaCoCo。目標 80%+,關鍵路徑 100%。
- **斷言工具**:優先選用 **AssertJ** (`assertThat`) 以提升閱讀性。
- **例外測試**:使用 `assertThatThrownBy(...)`
## 常用指令
- **Maven**`mvn verify` (執行測試並產出覆蓋率報告)。
- **Gradle**`./gradlew test jacocoTestReport`。
---
**核心原則**:保持測試速度快、具備隔離性且結果具備確定性 (Deterministic)。測試應專注於「行為」而非「實作細節」。