Go 測試模式
全面的 Go 測試模式,用於遵循 TDD 方法論撰寫可靠且可維護的測試。
使用時機
- 撰寫新的 Go 函式或方法時
- 為現有程式碼增加測試覆蓋率時
- 為效能關鍵程式碼建立基準測試時
- 為輸入驗證實作模糊測試時
- 在 Go 專案中遵循 TDD 工作流程時
Go 的 TDD 工作流程
RED-GREEN-REFACTOR 循環
RED → 先撰寫一個會失敗的測試
GREEN → 撰寫最少程式碼讓測試通過
REFACTOR → 改善程式碼,同時保持測試通過
REPEAT → 繼續下一個需求
Go 中的逐步 TDD
// 步驟 1:定義介面/簽章
// calculator.go
package calculator
func Add(a, b int) int {
panic("not implemented") // 佔位符
}
// 步驟 2:撰寫會失敗的測試 (RED)
// calculator_test.go
package calculator
import "testing"
func TestAdd(t *testing.T) {
got := Add(2, 3)
want := 5
if got != want {
t.Errorf("Add(2, 3) = %d; want %d", got, want)
}
}
// 步驟 3:執行測試 - 驗證 FAIL
// $ go test
// --- FAIL: TestAdd (0.00s)
// panic: not implemented
// 步驟 4:實作最少程式碼 (GREEN)
func Add(a, b int) int {
return a + b
}
// 步驟 5:執行測試 - 驗證 PASS
// $ go test
// PASS
// 步驟 6:視需要重構,並驗證測試仍通過
表格驅動測試
Go 測試的標準模式。以最少程式碼實現全面覆蓋。
func TestAdd(t *testing.T) {
tests := []struct {
name string
a, b int
expected int
}{
{"正數", 2, 3, 5},
{"負數", -1, -2, -3},
{"零值", 0, 0, 0},
{"混合正負號", -1, 1, 0},
{\