Langsung ke konten
Skillpedia
Testing280k Β· #187

golang-testing

Fungsinya

Alat ini membantu Anda membuat tes untuk kode Go. Alat ini mengajarkan pola-pola untuk memastikan kode Anda bekerja dengan benar dan mudah dirawat.

Kapan dipakai

  • βœ“Saat menulis fungsi Go baru.
  • βœ“Saat menambahkan tes ke kode yang sudah ada.
  • βœ“Saat membuat tes performa untuk bagian penting dari kode Anda.

Link skill

https://github.com/affaan-m/ECC/blob/main/pi/core/skills/golang-testing/SKILL.md

Salin lalu tempelkan ke AI Anda (Claude, ChatGPT, atau Cursor) dan minta AI mengikuti instruksinya.

Cara pakai

Cara paling mudah: salin pesan ini dan tempelkan ke AI Anda. AI akan membaca skill dan mengikuti instruksinya.

Pesan siap tempel

Gunakan skill ini untuk membantu saya: https://github.com/affaan-m/ECC/blob/main/pi/core/skills/golang-testing/SKILL.md Baca file SKILL.md di link tersebut dan ikuti instruksinya untuk tugas saya.
Mau AI Anda menemukan skill seperti ini sendiri?Pasang MCP Skillpedia gratis: cukup satu baris, dan AI mencari di antara 15.000+ skill sebelum tiap tugas.Pasang dalam 1 menit β†’

Contoh permintaan ke AI

β€œBagaimana cara membuat tes untuk fungsi Add yang memeriksa apakah 2 + 2 = 4?”

5 skill baru setiap minggu. 1 menit baca.

Cara kerjanya

Alat ini menggunakan metode bernama TDD (Test-Driven Development), di mana Anda menulis tes yang gagal terlebih dahulu, lalu menulis kode minimal agar tes tersebut lolos, dan terakhir merapikan kode (refactor). Dengan cara ini, kode Anda selalu teruji.

Konten teknis (SKILL.md asli)

Teks asli dari pembuat, dalam bahasa Inggris, langsung dari GitHub.

Go Testing Patterns

Comprehensive Go testing patterns for writing reliable, maintainable tests following TDD methodology.

When to Activate

  • Writing new Go functions or methods
  • Adding test coverage to existing code
  • Creating benchmarks for performance-critical code
  • Implementing fuzz tests for input validation
  • Following TDD workflow in Go projects

TDD Workflow for Go

The RED-GREEN-REFACTOR Cycle

RED     β†’ Write a failing test first
GREEN   β†’ Write minimal code to pass the test
REFACTOR β†’ Improve code while keeping tests green
REPEAT  β†’ Continue with next requirement

Step-by-Step TDD in Go

// Step 1: Define the interface/signature
// calculator.go
package calculator

func Add(a, b int) int {
    panic("not implemented") // Placeholder
}

// Step 2: Write failing test (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)
    }
}

// Step 3: Run test - verify FAIL
// $ go test
// --- FAIL: TestAdd (0.00s)
// panic: not implemented

// Step 4: Implement minimal code (GREEN)
func Add(a, b int) int {
    return a + b
}

// Step 5: Run test - verify PASS
// $ go test
// PASS

// Step 6: Refactor if needed, verify tests still pass

Table-Driven Tests

The standard pattern for Go tests. Enables comprehensive coverage with minimal code.

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)
            }
        })
    }
}

Table-Driven Tests with Error Cases

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{}, // Zero value 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)
            }
        })
    }
}

Subtests and Sub-benchmarks

Organizing Related Tests

func TestUser(t *testing.T) {
    // Setup shared by all subtests
    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) {
        // ...
    })
}

Parallel Subtests

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

    for _, tt := range tests {

…
Pertanyaan umum

Apa itu TDD?

TDD adalah singkatan dari Test-Driven Development. Ini adalah praktik menulis tes sebelum menulis kode yang sebenarnya. Tes tersebut membantu memandu pengembangan dan memastikan kode bekerja sesuai harapan.

Apa itu 'table-driven tests'?

Ini adalah cara yang terorganisir untuk menulis banyak tes bagi fungsi yang sama menggunakan daftar kasus uji. Cara ini membuat kode tes lebih rapi dan mudah dikelola.

Apa itu 'benchmarks'?

Benchmark adalah tes khusus yang mengukur performa kode Anda. Benchmark membantu menemukan bagian program yang lambat sehingga Anda bisa mengoptimalkannya.

Detail

Deskripsi asli dari pembuat

Go testing patterns including table-driven tests, subtests, benchmarks, fuzzing, and test coverage. Follows TDD methodology with idiomatic Go practices. Use when writing Go tests β€” table-driven cases, subtests, benchmarks, fuzzing, or coverage.

repo: affaan-m/ECC

Popularitas

Bintang GitHub
280k
Peringkat
#187
Lisensi
MIT
Diperbarui
15/10/2026

Apakah skill ini berguna?

0

Masuk untuk memberi suara.

Komentar

  • …

Skill lain dari repositori ini

Skill serupa