go-testing について
Go のテストを作成・実行する開発者向けのスキルです。慣用的なテストパターンに加え、ベンチマークやファジングも扱います。
主な機能
- 01テーブル駆動テストとサブテスト
- 02テストヘルパーとクリーンアップ
- 03インターフェースによる依存関係のモック
- 04HTTP ハンドラーテスト
- 05ベンチマークとファジング
活用シーン
- 01Go パッケージのテスト作成
- 02HTTP ハンドラーのテスト
- 03Go コードのベンチマークやファジング
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ autumnsgrove/ lattice --skill go-testingインストール後、Claude Code で/go-testingを入力して読み込まれたか確認します。
詳細
Go テストスキル
有効化するタイミング
次の場合にこのスキルを有効にします:
- Go のユニットテストを作成するとき
- テーブル駆動テストを作成するとき
- テストヘルパーやフィクスチャを扱うとき
- インターフェースを介して依存関係をモックするとき
- ベンチマークやファジングテストを実行するとき
クイックコマンド
# Run all tests
go test ./...
# Verbose output
go test -v ./...
# Run specific test
go test -run TestUserCreate
# With coverage
go test -cover ./...
go test -coverprofile=coverage.out ./...
go tool cover -html=coverage.out
# Run benchmarks
go test -bench=. ./...
# Race detector
go test -race ./...
基本的なテスト構造
// math_test.go
package math
import "testing"
func TestAdd(t *testing.T) {
result := Add(2, 3)
expected := 5
if result != expected {
t.Errorf("Add(2, 3) = %d; want %d", result, expected)
}
}
テーブル駆動テスト(Go らしい書き方)
func TestAdd(t *testing.T) {
tests := []struct {
name string
a, b int
expected int
}{
{"positive numbers", 2, 3, 5},
{"negative numbers", -1, -1, -2},
{"mixed signs", -1, 5, 4},
{"zeros", 0, 0, 0},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := Add(tt.a, tt.b)
if result != tt.expected {
t.Errorf("Add(%d, %d) = %d; want %d",
tt.a, tt.b, result, tt.expected)
}
})
}
}
サブテストと並列実行
func TestAPIEndpoints(t *testing.T) {
tests := []struct {
name string
endpoint string
status int
}{
{"health", "/health", 200},
{"users", "/api/users", 200},
}
for _, tt := range tests {
tt := tt // capture range variable
t.Run(tt.name, func(t *testing.T) {
t.Parallel() // run in parallel
// test logic
})
}
}
テストヘルパー
func assertEqual(t *testing.T, got, want int) {
t.Helper() // marks as helper for line numbers
if got != want {
t.Errorf("got %d; want %d", got, want)
}
}
func assertNoError(t *testing.T, err error) {
t.Helper()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
}
セットアップとティアダウン
func TestDatabase(t *testing.T) {
// Setup
db := setupTestDB(t)
// Teardown (runs after test)
t.Cleanup(func() {
db.Close()
})
// Test code
user, err := db.CreateUser("[email protected]")
assertNoError(t, err)
}
インターフェースによるモック
// Define interface for dependencies
type UserRepository interface {
FindByID(id string) (*User, error)
Save(user *User) error
}
// Mock implementation
type MockUserRepo struct {
FindByIDFunc func(id string) (*User, error)
}
func (m *MockUserRepo) FindByID(id string) (*User, error) {
return m.FindByIDFunc(id)
}
// Test with mock
func TestUserService_GetUser(t *testing.T) {
mock := &MockUserRepo{
FindByIDFunc: func(id string) (*User, error) {
return &User{ID: "123", Email: "[email protected]"}, nil
},
}
service := &UserService{repo: mock}
user, err := service.GetUser("123")
assertNoError(t, err)
assertEqual(t, user.ID, "123")
}
HTTP ハンドラーのテスト
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestHealthHandler(t *testing.T) {
req := httptest.NewRequest("GET", "/health", nil)
rr := httptest.NewRecorder()
handler := http.HandlerFunc(HealthHandler)
handler.ServeHTTP(rr, req)
if rr.Code != http.StatusOK {
t.Errorf("status = %d; want %d", rr.Code, http.StatusOK)
}
}
ベンチマーク
func BenchmarkAdd(b *testing.B) {
for i := 0; i < b.N; i++ {
Add(2, 3)
}
}
// Run: go test -bench=. -benchmem
ディレクトリ構造
project/
├── internal/
│ ├── user/
│ │ ├── user.go
│ │ └── user_test.go
│ └── api/
│ ├── handler.go
│ └── handler_test.go
└── test/
└── integration/
└── api_test.go
テスト関数のシグネチャ
func TestXxx(t *testing.T) // Regular test
func BenchmarkXxx(b *testing.B) // Benchmark
func ExampleXxx() // Example (docs)
func FuzzXxx(f *testing.F) // Fuzz test
関連リソース
ファジングテストのパターン、テスト種別のビルドタグ、パッケージレベルのセットアップに使う TestMain、CI でのカバレッジを含む完全なドキュメントについては、AgentUsage/testing_go.md を参照してください。
コメント
Markdown 対応