affaan-m/ECC

golang-testing

Go testing best practices including table-driven tests, test helpers, benchmarking, race detection, coverage analysis, and integration testing patterns. Use when writing or improving Go tests.

85CollectingRuns scripts
See how to use itView GitHub source
npx skills add https://github.com/affaan-m/ECC --skill ".kiro/skills/golang-testing"
Automated source guide

Source checked Jul 28, 2026·Refresh due Oct 26, 2026

Reorganized from the pinned upstream SKILL.md

Turn golang-testing's source instructions into a guide you can follow

According to the pinned SKILL.md from affaan-m/ECC: This skill provides comprehensive Go testing patterns extending common testing principles with Go-specific idioms.

npx skills add https://github.com/affaan-m/ECC --skill ".kiro/skills/golang-testing"
Check the pinned source

Best fit

  • Writing new Go tests
  • Improving test coverage
  • Setting up test infrastructure

Bring this context

  • A concrete task that matches the documented purpose of golang-testing.
  • The files, examples, or context the task depends on.
  • Your constraints, target environment, and definition of done.

Expected outputs

  • A result that follows the pinned golang-testing instructions.
  • A concise record of assumptions, inputs used, and unresolved questions.
  • A final check against the source workflow and relevant permission signals.

Key source sections

Read golang-testing through these 5 source sections

Sections are extracted automatically from the pinned SKILL.md and link back to the source.

01

Testing Framework

Use the standard go test with table-driven tests as the primary pattern.

SKILL.md · Testing Framework
Easy to add new test casesClear test case documentationParallel test execution with t.Parallel()
02

Table-Driven Tests

The idiomatic Go testing pattern:

SKILL.md · Table-Driven Tests
Easy to add new test casesClear test case documentationParallel test execution with t.Parallel()
03

Test Helpers

Use t.Helper() to mark helper functions:

SKILL.md · Test Helpers
Correct line numbers in test failuresReusable test utilitiesCleaner test code
05

Race Detection

Always run tests with the -race flag to detect data races:

SKILL.md · Race Detection
Detects concurrent access bugsPrevents production race conditionsMinimal performance overhead in tests

SkillSignal prompt templates

Provide the task, context, and acceptance criteria

These prompts were written by SkillSignal from the source structure; they are not upstream text.

Task-start prompt

Confirm source fit, inputs, and outputs before acting.

Use golang-testing to help me with: [specific task]. Context: [files, data, or background]. Constraints: [environment, scope, and prohibited actions]. Before acting, check the pinned SKILL.md and explain which sections apply, what inputs are still missing, and what you will deliver.

Source-guided execution

Make the Agent explicitly follow the key extracted sections.

Apply the pinned golang-testing source to [task]. Pay particular attention to these source sections: “Testing Framework”, “Table-Driven Tests”, “Test Helpers”, “Test Fixtures”, “Race Detection”. Preserve the important decision at each step. Mark facts not covered by the source as “needs confirmation” instead of inventing them. Then verify the result against my acceptance criteria: [criteria].

Result-review prompt

Check omissions, permissions, and source drift before delivery.

Review the current golang-testing result: (1) does it satisfy the original task; (2) were any applicable steps or limits in the pinned SKILL.md missed; (3) did it perform any unauthorized file, command, network, or data action; and (4) which conclusions remain unverified? List issues first, then fix only what the source or user authorization supports.

Output checklist

Verify each item before delivery

The task matches the purpose documented in the SKILL.md.

The source section “Testing Framework” has been checked.

The source section “Table-Driven Tests” has been checked.

The source section “Test Helpers” has been checked.

The source section “Test Fixtures” has been checked.

Inputs, constraints, and acceptance criteria are explicit.

Unverified facts, compatibility, and outcome claims are clearly marked.

Any file, command, network, or data action has been reviewed.

Choose a different workflow

When another Skill is the better fit

FAQ

What does golang-testing do?

This skill provides comprehensive Go testing patterns extending common testing principles with Go-specific idioms.

How do I start using golang-testing?

The catalog detected this source-specific install command: npx skills add https://github.com/affaan-m/ECC --skill ".kiro/skills/golang-testing". Inspect the command and pinned source before running it.

Which Agent platforms does it declare?

No dedicated Agent platform is declared in the pinned source record.

Repository stars
234,327
Repository forks
35,711
Quality
85/100
Source repository last pushed

Quality breakdown

Based on traceable docs and repository signals; stars are not treated as quality.

85/100
Documentation28/30
Specificity22/25
Maintenance20/20
Trust signals15/25
View original Skill.mdThis page is parsed directly from the repository SKILL.md without editorial rewriting. Collected: Jul 28, 2026 · about 2 min

Go Testing

This skill provides comprehensive Go testing patterns extending common testing principles with Go-specific idioms.

Testing Framework

Use the standard go test with table-driven tests as the primary pattern.

Table-Driven Tests

The idiomatic Go testing pattern:

func TestValidateEmail(t *testing.T) {
    tests := []struct {
        name    string
        email   string
        wantErr bool
    }{
        {
            name:    "valid email",
            email:   "user@example.com",
            wantErr: false,
        },
        {
            name:    "missing @",
            email:   "userexample.com",
            wantErr: true,
        },
        {
            name:    "empty string",
            email:   "",
            wantErr: true,
        },
    }

    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            err := ValidateEmail(tt.email)
            if (err != nil) != tt.wantErr {
                t.Errorf("ValidateEmail(%q) error = %v, wantErr %v",
                    tt.email, err, tt.wantErr)
            }
        })
    }
}

Benefits:

  • Easy to add new test cases
  • Clear test case documentation
  • Parallel test execution with t.Parallel()
  • Isolated subtests with t.Run()

Test Helpers

Use t.Helper() to mark helper functions:

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

func assertEqual(t *testing.T, got, want interface{}) {
    t.Helper()
    if !reflect.DeepEqual(got, want) {
        t.Errorf("got %v, want %v", got, want)
    }
}

Benefits:

  • Correct line numbers in test failures
  • Reusable test utilities
  • Cleaner test code

Test Fixtures

Use t.Cleanup() for resource cleanup:

func testDB(t *testing.T) *sql.DB {
    t.Helper()

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

    // Cleanup runs after test completes
    t.Cleanup(func() {
        if err := db.Close(); err != nil {
            t.Errorf("failed to close db: %v", err)
        }
    })

    return db
}

func TestUserRepository(t *testing.T) {
    db := testDB(t)
    repo := NewUserRepository(db)
    // ... test logic
}

Race Detection

Always run tests with the -race flag to detect data races:

go test -race ./...

In CI/CD:

- name: Test with race detector
  run: go test -race -timeout 5m ./...

Why:

  • Detects concurrent access bugs
  • Prevents production race conditions
  • Minimal performance overhead in tests

Coverage Analysis

Basic Coverage

go test -cover ./...

Detailed Coverage Report

go test -coverprofile=coverage.out ./...
go tool cover -html=coverage.out

Coverage Thresholds

# Fail if coverage below 80%
go test -cover ./... | grep -E 'coverage: [0-7][0-9]\.[0-9]%' && exit 1

Benchmarking

func BenchmarkValidateEmail(b *testing.B) {
    email := "user@example.com"

    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        ValidateEmail(email)
    }
}

Run benchmarks:

go test -bench=. -benchmem

Compare benchmarks:

go test -bench=. -benchmem > old.txt
# make changes
go test -bench=. -benchmem > new.txt
benchstat old.txt new.txt

Mocking

Interface-Based Mocking

type UserRepository interface {
    GetUser(id string) (*User, error)
}

type mockUserRepository struct {
    users map[string]*User
    err   error
}

func (m *mockUserRepository) GetUser(id string) (*User, error) {
    if m.err != nil {
        return nil, m.err
    }
    return m.users[id], nil
}

func TestUserService(t *testing.T) {
    mock := &mockUserRepository{
        users: map[string]*User{
            "1": {ID: "1", Name: "Alice"},
        },
    }

    service := NewUserService(mock)
    // ... test logic
}

Integration Tests

Build Tags

//go:build integration
// +build integration

package user_test

func TestUserRepository_Integration(t *testing.T) {
    // ... integration test
}

Run integration tests:

go test -tags=integration ./...

Test Containers

func TestWithPostgres(t *testing.T) {
    if testing.Short() {
        t.Skip("skipping integration test")
    }

    // Setup test container
    ctx := context.Background()
    container, err := testcontainers.GenericContainer(ctx, ...)
    assertNoError(t, err)

    t.Cleanup(func() {
        container.Terminate(ctx)
    })

    // ... test logic
}

Test Organization

File Structure

package/
├── user.go
├── user_test.go          # Unit tests
├── user_integration_test.go  # Integration tests
└── testdata/             # Test fixtures
    └── users.json

Package Naming

// Black-box testing (external perspective)
package user_test

// White-box testing (internal access)
package user

Common Patterns

Testing HTTP Handlers

func TestUserHandler(t *testing.T) {
    req := httptest.NewRequest("GET", "/users/1", nil)
    rec := httptest.NewRecorder()

    handler := NewUserHandler(mockRepo)
    handler.ServeHTTP(rec, req)

    assertEqual(t, rec.Code, http.StatusOK)
}

Testing with Context

func TestWithTimeout(t *testing.T) {
    ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
    defer cancel()

    err := SlowOperation(ctx)
    if !errors.Is(err, context.DeadlineExceeded) {
        t.Errorf("expected timeout error, got %v", err)
    }
}

Best Practices

  1. Use t.Parallel() for independent tests
  2. Use testing.Short() to skip slow tests
  3. Use t.TempDir() for temporary directories
  4. Use t.Setenv() for environment variables
  5. Avoid init() in test files
  6. Keep tests focused - one behavior per test
  7. Use meaningful test names - describe what's being tested

When to Use This Skill

  • Writing new Go tests
  • Improving test coverage
  • Setting up test infrastructure
  • Debugging flaky tests
  • Optimizing test performance
  • Implementing integration tests
Source repo
affaan-m/ECC
Skill path
.kiro/skills/golang-testing/SKILL.md
Commit SHA
4e973d3eaf92
Repository license
MIT
Data collected