Communitygithub.com

golang-testing

Go 테스트 패턴: 테이블 기반 테스트, 하위 테스트, 벤치마크, 퍼징, 테스트 커버리지. TDD 방법론과 Go 관용구를 따릅니다. Go 테스트 작성 시 사용하세요 — 테이블 기반 케이스, 하위 테스트, 벤치마크, 퍼징 또는 커버리지.

golang-testing란 무엇인가요?

이 스킬은 Go에서 안정적이고 유지보수 가능한 테스트를 작성하기 위한 포괄적인 패턴을 제공합니다. 테이블 기반 테스트, 하위 테스트 및 하위 벤치마크, 골든 파일, 인터페이스 기반 목(mock) 객체 등 다양한 테스트 패턴을 다룹니다. RED-GREEN-REFACTOR 주기를 사용한 TDD 워크플로우를 지원하며, 벤치마킹(기본, 크기별, 메모리 할당), 퍼징(Go 1.18+), HTTP 핸들러 테스트, 테스트 커버리지 분석 및 목표 설정에 대한 지침을 포함합니다. 모든 코드 예제와 패턴은 Go 관용구를 따르며, 도우미 함수, 임시 파일, 클린업 등 실제 Go 테스트 모범 사례를 강조합니다.

지원 대상~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/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
    }{
        {"positive numbers", 2, 3, 5},
        {"negative numbers", -1, -2, -3},
        {"zero values", 0, 0, 0},
        {"mixed signs", -1, 1, 0},
        {"large numbers", 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:  "valid config",
            input: `{"host": "localhost", "port": 8080}`,
            want:  &Config{Host: "localhost", Port: 8080},
        },
        {
            name:    "invalid JSON",
            input:   `{invalid}`,
            wantErr: true,
        },
        {
            name:    "empty input",
            input:   "",
            wantErr: true,
        },
        {
            name:  "minimal config",
            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("Create", 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("Get", 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("Update", func(t *testing.T) {
        // ...
    })

    t.Run("Delete", 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
    }{
        {"simple", Template{Name: "test"}},
        {"complex", 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) {
    // 실제 데이터베이스 쿼리
}

// 테스트용 목 구현
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)
}

// 목을 사용한 테스트
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:       "get user",
            method:     http.MethodGet,
            path:       "/users/123",
            wantStatus: http.StatusOK,
            wantBody:   `{"id":"123","name":"Alice"}`,
        },
        {
            name:       "not found",
            method:     http.MethodGet,
            path:       "/users/999",
            wantStatus: http.StatusNotFound,
        },
        {
            name:       "create user",
            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) {
            var reqBody io.Reader
            if tt.body != "" {
                reqBody = strings.NewReader(tt.body)
            }
            req := httptest.NewRequest(tt.method, tt.path, reqBody)
            w := httptest.NewRecorder()

            handler.ServeHTTP(w, req)

            resp := w.Result()
            defer resp.Body.Close()

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

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

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/claude-api

Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.

affaan-m/everything-claude-code

End-to-end marketing campaign planning and execution. Covers audience research, positioning, campaign angle definition, landing page copy, email sequences, social posts, ad copy, short-form video scripts, and content calendars. Use as the orchestration layer for multi-channel product launches. Use when planning or executing a multi-channel product launch, or producing landing page, email, social, or ad copy.

affaan-m/everything-claude-code

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/everything-claude-code-conventions

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/frontend-design

Create distinctive, production-grade frontend interfaces with high design quality. Use when the user asks to build web components, pages, or applications and the visual direction matters as much as the code quality.

affaan-m/gget

gget CLI and Python workflow for quick genomic database queries, sequence lookup, BLAST-style searches, enrichment checks, and reproducible bioinformatics evidence logs.

affaan-m/literature-review

Systematic literature-review workflow for academic, biomedical, technical, and scientific topics, including search planning, source screening, synthesis, citation checks, and evidence logging.

affaan-m/motion-ui

Production-ready UI motion system for React/Next.js. Use when implementing animations, transitions, or motion patterns.

affaan-m/project-guidelines-example

Example project-specific skill template based on a real production application.

affaan-m/pubmed-database

Direct PubMed and NCBI E-utilities search workflows for biomedical literature, MeSH queries, PMID lookup, citation retrieval, and API-backed literature monitoring.

affaan-m/scholar-evaluation

Structured scholarly-work evaluation for papers, proposals, literature reviews, methods sections, evidence quality, citation support, and research-writing feedback.

affaan-m/uspto-database

USPTO patent and trademark data workflow for official record lookup, PatentSearch queries, TSDR checks, assignment data, and reproducible IP research logs.

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.

관련 스킬