測試檔案規範#
Go 的測試框架有嚴格的命名規範:
mypackage/
├── calculator.go # 原始碼
├── calculator_test.go # 測試檔案(必須以 _test.go 結尾)
└── helper_test.go # 測試輔助檔案測試檔案規則:
- 檔名必須以
_test.go結尾- 測試檔案會被
go build忽略,只有go test會編譯- 測試檔案可以存取同套件的私有成員
測試函式分類#
import "testing"
// 功能測試:以 Test 開頭
func TestAdd(t *testing.T) {
result := Add(2, 3)
if result != 5 {
t.Errorf("Add(2, 3) = %d; want 5", result)
}
}
// 基準測試:以 Benchmark 開頭
func BenchmarkAdd(b *testing.B) {
for i := 0; i < b.N; i++ {
Add(2, 3)
}
}
// 範例測試:以 Example 開頭
func ExampleAdd() {
fmt.Println(Add(2, 3))
// Output: 5
}測試函式命名#
// 測試函式命名規則:Test + 被測函式名 + 描述
func TestCalculator_Add(t *testing.T) { ... }
func TestCalculator_Add_NegativeNumbers(t *testing.T) { ... }
func TestCalculator_Add_Overflow(t *testing.T) { ... }
// 範例函式命名規則
func ExampleCalculator() { ... } // 套件範例
func ExampleCalculator_Add() { ... } // 方法範例
func Example_helper() { ... } // 私有函式範例