Skip to content
go-test-generator logo

Go テスト生成パターン

go-test-generator

Goのテストコードを生成する際に使用。テーブル駆動テスト、testify/assert使用、命名規則TestStructName_MethodNameを適用。Goのユニットテスト、統合テストを書く場合に使用。

SKILL.md

Full skill instructions

Go テスト生成パターン

このプロジェクトのGoテスト実装パターンを定義します。

命名規則

  • ファイル名: *_test.go
  • 関数名: TestStructName_MethodName または TestFunctionName
  • パッケージ名: {package}_test (外部テスト) または {package} (内部テスト)

使用ライブラリ

import (
    "testing"

    "github.com/​stretchr/​testify/​assert"
    "github.com/​stretchr/​testify/​require"
)
  • assert: テスト失敗しても続行
  • require: テスト失敗で即座に中断

参照ファイル

テスト実装の参照:

  • server/​internal/​repository/​user_repository_test.go - Repository テスト
  • server/​internal/​db/​sharding_test.go - シャーディングテスト
  • server/​test/​integration/ - 統合テスト

テストユーティリティ:

  • server/​test/​testutil/ - テストヘルパー

コードパターン

1. 基本的なテスト

func TestStructName_MethodName(t *testing.T) {
    // Arrange
    expected := "expected value"

    // Act
    actual := SomeFunction()

    // Assert
    assert.Equal(t, expected, actual)
}

2. シャーディング対応のテスト

func TestUserRepository_Create(t *testing.T) {
    // テスト用GroupManagerのセットアップ
    groupManager := testutil.SetupTestGroupManager(t, 4, 8)
    defer testutil.CleanupTestGroupManager(groupManager)

    repo := repository.NewUserRepository(groupManager)
    ctx := context.Background()

    req := &model.CreateUserRequest{
        Name:  "Test User",
        Email: "[email protected]",
    }

    user, err := repo.Create(ctx, req)
    assert.NoError(t, err)
    assert.NotNil(t, user)
    assert.NotZero(t, user.ID)
}

3. テーブル駆動テスト

func TestHashBasedSharding_GetShardID(t *testing.T) {
    tests := []struct {
        name       string
        shardCount int
        key        int64
        wantMin    int
        wantMax    int
    }{
        {
            name:       "single shard",
            shardCount: 1,
            key:        12345,
            wantMin:    1,
            wantMax:    1,
        },
        {
            name:       "multiple shards",
            shardCount: 4,
            key:        12345,
            wantMin:    1,
            wantMax:    4,
        },
    }

    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            sharding := db.NewHashBasedSharding(tt.shardCount)
            got := sharding.GetShardID(tt.key)

            assert.GreaterOrEqual(t, got, tt.wantMin)
            assert.LessOrEqual(t, got, tt.wantMax)
        })
    }
}

4. エラーケースのテスト

func TestUserRepository_GetByID_NotFound(t *testing.T) {
    groupManager := testutil.SetupTestGroupManager(t, 4, 8)
    defer testutil.CleanupTestGroupManager(groupManager)

    repo := repository.NewUserRepository(groupManager)
    ctx := context.Background()

    // 存在しないIDでテスト
    user, err := repo.GetByID(ctx, 999)
    assert.Error(t, err)
    assert.Nil(t, user)
}

5. require vs assert の使い分け

func TestUserRepository_Update(t *testing.T) {
    groupManager := testutil.SetupTestGroupManager(t, 4, 8)
    defer testutil.CleanupTestGroupManager(groupManager)

    repo := repository.NewUserRepository(groupManager)
    ctx := context.Background()

    // 前提条件の確認には require を使用(失敗時は即座に中断)
    created, err := repo.Create(ctx, createReq)
    require.NoError(t, err)

    // 本テストの検証には assert を使用
    updated, err := repo.Update(ctx, created.ID, updateReq)
    assert.NoError(t, err)
    assert.Equal(t, "Updated Name", updated.Name)
}

テスト実行コマンド

# 全テスト実行
cd server && APP_ENV=develop go test ./​...

# 特定パッケージのテスト
cd server && APP_ENV=develop go test ./​internal/​repository/​...

# 詳細出力
cd server && APP_ENV=develop go test -v ./​...

# カバレッジ
cd server && APP_ENV=develop go test -cover ./​...

More skills from majiayu000

xiaohongshu logo
majiayu000/claude-arsenal

xiaohongshu

xiaohongshu

286 148
View
agent-task-conductor logo
majiayu000/claude-skill-registry

agent-task-conductor

Conduct multi-agent task orchestration and workflow coordination.

663 1
View
conductor-setup logo
majiayu000/claude-skill-registry

conductor-setup

Initialize project with Conductor artifacts (product definition,

663 1
View
animation-designer logo
majiayu000/claude-skill-registry

animation-designer

Expert in web animations, transitions, and motion design using Framer Motion and CSS

663 1
View
diagramming logo
majiayu000/claude-skill-registry

diagramming

Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...

663 1
View
h3-pg logo
majiayu000/claude-skill-registry-data

h3-pg

PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.

23 1
View
conductor-development logo
majiayu000/claude-skill-registry

conductor-development

Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...

663 1
View
conductor-status logo
majiayu000/claude-skill-registry

conductor-status

Display project status, active tracks, and next actions

663 1
View
dockerization logo
majiayu000/claude-skill-registry

dockerization

Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.

663 1
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View