Communitygithub.com

golang-testing

테이블 기반 테스트, 서브테스트, 벤치마크, 퍼징, 테스트 커버리지를 포함한 Go 테스트 패턴. TDD 방법론과 관용적인 Go 방식을 따릅니다. Go 테스트 작성 시 사용하세요 — 테이블 기반 케이스, 서브테스트, 벤치마크, 퍼징 또는 커버리지.

golang-testing란 무엇인가요?

이 스킬은 Go 프로그래밍 언어를 위한 모범 사례 테스트 패턴을 제공합니다. Claude Code와 같은 AI 에이전트가 TDD(테스트 주도 개발) 방법론을 준수하면서 신뢰할 수 있고 유지 관리하기 쉬운 Go 테스트를 작성하도록 안내합니다. 이 스킬은 테이블 기반 테스트(Go의 표준 테스트 패턴), 서브테스트 및 하위 벤치마크, 골든 파일, 인터페이스 기반 모킹, 벤치마크(메모리 할당 분석 포함), 퍼징(Go 1.18+), HTTP 핸들러 테스트 등 다양한 테스트 유형과 시나리오를 다룹니다. 또한 RED-GREEN-REFACTOR 주기를 단계별 예제와 함께 제공하여 TDD 워크플로우를 강조합니다. 각 패턴은 AI 에이전트가 사용자의 특정 요구에 맞게 쉽게 복사, 수정 및 적용할 수 있는 완전한 코드 예제와 함께 제공됩니다. 이 스킬은 모든 주요 에이전트 플랫폼(Claude Code, Cursor, Windsurf, VS Code 및 기타 터미널 기반 에이전트)을 지원하며, Go 개발자 또는 AI 에이전트가 Go 표준 라이브러리 및 관용적 규칙을 사용하여 고품질 테스트를 신속하게 생성할 수 있도록 합니다.

지원 대상~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/ECC/tree/main/skills/golang-testing

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

Go 테스트 패턴

TDD 방법론을 따라 신뢰할 수 있고 유지 관리하기 쉬운 테스트를 작성하기 위한 포괄적인 Go 테스트 패턴입니다.

활성화 시기

  • 새로운 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, 0},
        {"부호 혼합", -1, 1, 0},
        {"큰 수", 1000000, 2000000, 3000000},
    }

    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            got := Add(tt.a, tt.b)
            if got != tt.expected {
                t.Errorf("Add(%d, %d) = %d; want %d",
                    tt.a, tt.b, got, tt.expected)
            }
        })
    }
}

오류 케이스가 있는 테이블 기반 테스트

func TestParseConfig(t *testing.T) {
    tests := []struct {
        name    string
        input   string
        want    *Config
        wantErr bool
    }{
        {
            name:  "유효한 설정",
            input: `{"host": "localhost", "port": 8080}`,
            want:  &Config{Host: "localhost", Port: 8080},
        },
        {
            name:    "잘못된 JSON",
            input:   `{invalid}`,
            wantErr: true,
        },
        {
            name:    "빈 입력",
            input:   "",
            wantErr: true,
        },
        {
            name:  "최소 설정",
            input: `{}`,
            want:  &Config{}, // 제로 값 설정
        },
    }

    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            got, err := ParseConfig(tt.input)

            if tt.wantErr {
                if err == nil {
                    t.Error("expected error, got nil")
                }
                return
            }

            if err != nil {
                t.Fatalf("unexpected error: %v", err)
            }

            if !reflect.DeepEqual(got, tt.want) {
                t.Errorf("got %+v; want %+v", got, tt.want)
            }
        })
    }
}

서브테스트 및 서브벤치마크

관련 테스트 구성

func TestUser(t *testing.T) {
    // 모든 서브테스트에서 공유하는 설정
    db := setupTestDB(t)

    t.Run("생성", func(t *testing.T) {
        user := &User{Name: "Alice"}
        err := db.CreateUser(user)
        if err != nil {
            t.Fatalf("CreateUser failed: %v", err)
        }
        if user.ID == "" {
            t.Error("expected user ID to be set")
        }
    })

    t.Run("조회", func(t *testing.T) {
        user, err := db.GetUser("alice-id")
        if err != nil {
            t.Fatalf("GetUser failed: %v", err)
        }
        if user.Name != "Alice" {
            t.Errorf("got name %q; want %q", user.Name, "Alice")
        }
    })

    t.Run("수정", func(t *testing.T) {
        // ...
    })

    t.Run("삭제", func(t *testing.T) {
        // ...
    })
}

병렬 서브테스트

func TestParallel(t *testing.T) {
    tests := []struct {
        name  string
        input string
    }{
        {"case1", "input1"},
        {"case2", "input2"},
        {"case3", "input3"},
    }

    for _, tt := range tests {
        tt := tt // 범위 변수 캡처
        t.Run(tt.name, func(t *testing.T) {
            t.Parallel() // 서브테스트를 병렬로 실행
            result := Process(tt.input)
            // assertions...
            _ = result
        })
    }
}

테스트 헬퍼

헬퍼 함수

func setupTestDB(t *testing.T) *sql.DB {
    t.Helper() // 이 함수를 헬퍼 함수로 표시

    db, err := sql.Open("sqlite3", ":memory:")
    if err != nil {
        t.Fatalf("failed to open database: %v", err)
    }

    // 테스트 완료 시 정리
    t.Cleanup(func() {
        db.Close()
    })

    // 마이그레이션 실행
    if _, err := db.Exec(schema); err != nil {
        t.Fatalf("failed to create schema: %v", err)
    }

    return db
}

func assertNoError(t *testing.T, err error) {
    t.Helper()
    if err != nil {
        t.Fatalf("unexpected error: %v", err)
    }
}

func assertEqual[T comparable](t *testing.T, got, want T) {
    t.Helper()
    if got != want {
        t.Errorf("got %v; want %v", got, want)
    }
}

임시 파일 및 디렉토리

func TestFileProcessing(t *testing.T) {
    // 임시 디렉토리 생성 - 자동으로 정리됨
    tmpDir := t.TempDir()

    // 테스트 파일 생성
    testFile := filepath.Join(tmpDir, "test.txt")
    err := os.WriteFile(testFile, []byte("test content"), 0644)
    if err != nil {
        t.Fatalf("failed to create test file: %v", err)
    }

    // 테스트 실행
    result, err := ProcessFile(testFile)
    if err != nil {
        t.Fatalf("ProcessFile failed: %v", err)
    }

    // Assert...
    _ = result
}

골든 파일

testdata/에 저장된 예상 출력 파일에 대한 테스트입니다.

var update = flag.Bool("update", false, "update golden files")

func TestRender(t *testing.T) {
    tests := []struct {
        name  string
        input Template
    }{
        {"단순", Template{Name: "test"}},
        {"복합", Template{Name: "test", Items: []string{"a", "b"}}},
    }

    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            got := Render(tt.input)

            golden := filepath.Join("testdata", tt.name+".golden")

            if *update {
                // 골든 파일 업데이트: go test -update
                err := os.WriteFile(golden, got, 0644)
                if err != nil {
                    t.Fatalf("failed to update golden file: %v", err)
                }
            }

            want, err := os.ReadFile(golden)
            if err != nil {
                t.Fatalf("failed to read golden file: %v", err)
            }

            if !bytes.Equal(got, want) {
                t.Errorf("output mismatch:\ngot:\n%s\nwant:\n%s", got, want)
            }
        })
    }
}

인터페이스를 사용한 모킹

인터페이스 기반 모킹

// 의존성을 위한 인터페이스 정의
type UserRepository interface {
    GetUser(id string) (*User, error)
    SaveUser(user *User) error
}

// 프로덕션 구현
type PostgresUserRepository struct {
    db *sql.DB
}

func (r *PostgresUserRepository) GetUser(id string) (*User, error) {
    // 실제 데이터베이스 쿼리
}

// 테스트를 위한 Mock 구현
type MockUserRepository struct {
    GetUserFunc  func(id string) (*User, error)
    SaveUserFunc func(user *User) error
}

func (m *MockUserRepository) GetUser(id string) (*User, error) {
    return m.GetUserFunc(id)
}

func (m *MockUserRepository) SaveUser(user *User) error {
    return m.SaveUserFunc(user)
}

// Mock을 사용한 테스트
func TestUserService(t *testing.T) {
    mock := &MockUserRepository{
        GetUserFunc: func(id string) (*User, error) {
            if id == "123" {
                return &User{ID: "123", Name: "Alice"}, nil
            }
            return nil, ErrNotFound
        },
    }

    service := NewUserService(mock)

    user, err := service.GetUserProfile("123")
    if err != nil {
        t.Fatalf("unexpected error: %v", err)
    }
    if user.Name != "Alice" {
        t.Errorf("got name %q; want %q", user.Name, "Alice")
    }
}

벤치마크

기본 벤치마크

func BenchmarkProcess(b *testing.B) {
    data := generateTestData(1000)
    b.ResetTimer() // 설정 시간은 계산하지 않음

    for i := 0; i < b.N; i++ {
        Process(data)
    }
}

// 실행: go test -bench=BenchmarkProcess -benchmem
// 출력: BenchmarkProcess-8   10000   105234 ns/op   4096 B/op   10 allocs/op

다양한 크기의 벤치마크

func BenchmarkSort(b *testing.B) {
    sizes := []int{100, 1000, 10000, 100000}

    for _, size := range sizes {
        b.Run(fmt.Sprintf("size=%d", size), func(b *testing.B) {
            data := generateRandomSlice(size)
            b.ResetTimer()

            for i := 0; i < b.N; i++ {
                // 이미 정렬된 데이터를 정렬하지 않도록 복사
                tmp := make([]int, len(data))
                copy(tmp, data)
                sort.Ints(tmp)
            }
        })
    }
}

메모리 할당 벤치마크

func BenchmarkStringConcat(b *testing.B) {
    parts := []string{"hello", "world", "foo", "bar", "baz"}

    b.Run("plus", func(b *testing.B) {
        for i := 0; i < b.N; i++ {
            var s string
            for _, p := range parts {
                s += p
            }
            _ = s
        }
    })

    b.Run("builder", func(b *testing.B) {
        for i := 0; i < b.N; i++ {
            var sb strings.Builder
            for _, p := range parts {
                sb.WriteString(p)
            }
            _ = sb.String()
        }
    })

    b.Run("join", func(b *testing.B) {
        for i := 0; i < b.N; i++ {
            _ = strings.Join(parts, "")
        }
    })
}

퍼징 (Go 1.18+)

기본 퍼지 테스트

func FuzzParseJSON(f *testing.F) {
    // 시드 코퍼스 추가
    f.Add(`{"name": "test"}`)
    f.Add(`{"count": 123}`)
    f.Add(`[]`)
    f.Add(`""`)

    f.Fuzz(func(t *testing.T, input string) {
        var result map[string]interface{}
        err := json.Unmarshal([]byte(input), &result)

        if err != nil {
            // 잘못된 JSON은 무작위 입력에서 예상됨
            return
        }

        // 파싱이 성공하면 다시 인코딩도 작동해야 함
        _, err = json.Marshal(result)
        if err != nil {
            t.Errorf("Marshal failed after successful Unmarshal: %v", err)
        }
    })
}

// 실행: go test -fuzz=FuzzParseJSON -fuzztime=30s

여러 입력이 있는 퍼지 테스트

func FuzzCompare(f *testing.F) {
    f.Add("hello", "world")
    f.Add("", "")
    f.Add("abc", "abc")

    f.Fuzz(func(t *testing.T, a, b string) {
        result := Compare(a, b)

        // 속성: Compare(a, a)는 항상 0이어야 함
        if a == b && result != 0 {
            t.Errorf("Compare(%q, %q) = %d; want 0", a, b, result)
        }

        // 속성: Compare(a, b)와 Compare(b, a)는 반대 부호를 가져야 함
        reverse := Compare(b, a)
        if (result > 0 && reverse >= 0) || (result < 0 && reverse <= 0) {
            if result != 0 || reverse != 0 {
                t.Errorf("Compare(%q, %q) = %d, Compare(%q, %q) = %d; inconsistent",
                    a, b, result, b, a, reverse)
            }
        }
    })
}

테스트 커버리지

커버리지 실행

# 기본 커버리지
go test -cover ./...

# 커버리지 프로파일 생성
go test -coverprofile=coverage.out ./...

# 브라우저에서 커버리지 보기
go tool cover -html=coverage.out

# 함수별 커버리지 보기
go tool cover -func=coverage.out

# 레이스 탐지와 함께 커버리지
go test -race -coverprofile=coverage.out ./...

커버리지 목표

코드 유형목표
중요 비즈니스 로직100%
공개 API90%+
일반 코드80%+
생성된 코드제외

커버리지에서 생성된 코드 제외

//go:generate mockgen -source=interface.go -destination=mock_interface.go

// 커버리지 프로파일에서 빌드 태그로 제외:
// go test -cover -tags=!generate ./...

HTTP 핸들러 테스트

func TestHealthHandler(t *testing.T) {
    // 요청 생성
    req := httptest.NewRequest(http.MethodGet, "/health", nil)
    w := httptest.NewRecorder()

    // 핸들러 호출
    HealthHandler(w, req)

    // 응답 확인
    resp := w.Result()
    defer resp.Body.Close()

    if resp.StatusCode != http.StatusOK {
        t.Errorf("got status %d; want %d", resp.StatusCode, http.StatusOK)
    }

    body, _ := io.ReadAll(resp.Body)
    if string(body) != "OK" {
        t.Errorf("got body %q; want %q", body, "OK")
    }
}

func TestAPIHandler(t *testing.T) {
    tests := []struct {
        name       string
        method     string
        path       string
        body       string
        wantStatus int
        wantBody   string
    }{
        {
            name:       "사용자 조회",
            method:     http.MethodGet,
            path:       "/users/123",
            wantStatus: http.StatusOK,
            wantBody:   `{"id":"123","name":"Alice"}`,
        },
        {
            name:       "찾을 수 없음",
            method:     http.MethodGet,
            path:       "/users/999",
            wantStatus: http.StatusNotFound,
        },
        {
            name:       "사용자 생성",
            method:     http.MethodPost,
            path:       "/users",
            body:       `{"name":"Bob"}`,
            wantStatus: http.StatusCreated,
        },
    }

    handler := NewAPIHandler()

    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            // ...
        })
    }
}

Go 테스트 모범 사례

파일 구조

package/
├── calculator.go          # 프로덕션 코드
├── calculator_test.go     # 테스트 파일 (calculator 테스트)
├── export_test.go         # 테스트용 내보내기 (선택 사항)
└── testdata/              # 테스트 데이터 파일
    ├── input.txt
    └── expected.golden

명명 규칙

요소규칙예시
테스트 함수TestXxxTestAdd
벤치마크 함수BenchmarkXxxBenchmarkSort
퍼지 함수FuzzXxxFuzzParseJSON
테스트 파일*_test.gocalculator_test.go
테이블 행설명적 이름{"edge case"}

중요 원칙

  1. 격리: 테스트는 공유 상태에 의존해서는 안 됩니다.
  2. 결정론적: 동일한 입력은 항상 동일한 결과를 생성해야 합니다.
  3. 설명적: 테스트 이름은 시나리오를 설명해야 합니다.
  4. 단일 책임: 각 테스트는 한 가지를 확인해야 합니다.
  5. 최소화: 필요한 것만 테스트하고 불필요한 주장을 피하십시오.

일반적인 함정

// 잘못됨: 범위 변수 캡처
for _, tt := range tests {
    go func() {
        Process(tt.input) // goroutine이 실행될 때 tt가 변경됨
    }()
}

// 올바름: 범위 변수 캡처
for _, tt := range tests {
    tt := tt // 로컬 변수 생성
    go func() {
        Process(tt.input)
    }()
}

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/content-engine

Create platform-native content systems for X, LinkedIn, TikTok, YouTube, newsletters, and repurposed multi-platform campaigns. Use when the user wants social posts, threads, scripts, content calendars, or one source asset adapted cleanly across platforms.

affaan-m/ECC

Multi-platform content distribution across X, LinkedIn, Threads, and Bluesky. Adapts content per platform using content-engine patterns. Never posts identical content cross-platform. Use when the user wants to distribute content across social platforms.

affaan-m/fal-ai-media

Unified media generation via fal.ai MCP — image, video, and audio. Covers text-to-image (Nano Banana), text/image-to-video (Seedance, Kling, Veo 3), text-to-speech (CSM-1B), and video-to-audio (ThinkSound). Use when the user wants to generate images, videos, or audio with AI.

affaan-m/manim-video

日本語翻訳:このファイルは manim-video 用の日本語翻訳が必要です

affaan-m/remotion-video-creation

Remotion のベストプラクティス - React で動画を作成する。3D、アニメーション、音声、字幕、チャート、トランジションなどをカバーするドメイン固有の29のルール。

affaan-m/video-editing

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

agent-sort

Build an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.

ai-first-engineering

Engineering operating model for teams where AI agents generate a large share of implementation output. Use when setting team process, review gates, or ownership rules for a codebase largely written by agents.

ai-regression-testing

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code. Use when adding regression coverage to AI-assisted code, or when the same model both wrote and reviewed a change.

android-clean-architecture

Clean Architecture patterns for Android and Kotlin Multiplatform projects — module structure, dependency rules, UseCases, Repositories, and data layer patterns. Use when structuring modules, layers, or data flow in an Android or KMP project.

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

관련 스킬