Pular para o conteúdo
Skillpedia
Testes280 mil · #62

golang-testing

Faz seu agente criar testes em Go, como testes baseados em tabelas e benchmarks. Ajuda a garantir a qualidade do código seguindo a metodologia TDD.

O que ela faz

Esta ferramenta ajuda a criar testes para o seu código em Go. Ela ensina padrões para garantir que seu código funcione corretamente e seja fácil de manter.

Quando usar

  • ✓Ao escrever novas funções em Go.
  • ✓Ao adicionar testes a um código já existente.
  • ✓Ao criar testes de desempenho para partes importantes do seu código.

Exemplo do que pedir para a IA

“Como posso escrever um teste para a função Add que verifica se 2 + 2 = 4?”

Quer saber mais? Abra as seções abaixo.

Como usar

O jeito mais fácil: copie a mensagem abaixo e cole no Claude, ChatGPT, Cursor ou outra IA. Ela lê a skill e segue as instruções.

Link da skill

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

Mensagem pronta para colar

Use esta skill para me ajudar: https://github.com/affaan-m/ECC/blob/main/pi/core/skills/golang-testing/SKILL.md Leia o arquivo SKILL.md desse link e siga as instruções dele na minha tarefa.
Como funciona

Ela usa um método chamado TDD (Desenvolvimento Guiado por Testes), onde você escreve um teste que falha primeiro, depois escreve o código mínimo para fazê-lo passar, e por fim refatora o código. Isso garante que seu código esteja sempre testado.

Instalação

Jeito mais fácil: copie o link da skill e cole no Claude, ChatGPT ou Cursor pedindo para seguir as instruções.

No terminal (Claude Code, Codex, Cursor), na pasta do projeto:

npx skills add affaan-m/ECC --skill golang-testing

Ou baixe só o arquivo:

curl -L https://raw.githubusercontent.com/affaan-m/ECC/main/pi/core/skills/golang-testing/SKILL.md -o SKILL.md
Conteúdo técnico (SKILL.md)

Tradução do texto original do autor no GitHub. Os comandos e códigos estão como no original.

Padrões de Teste em Go

Padrões abrangentes de teste em Go para escrever testes confiáveis e fáceis de manter, seguindo a metodologia TDD.

Quando Ativar

  • Escrevendo novas funções ou métodos em Go
  • Adicionando cobertura de teste a código existente
  • Criando benchmarks para código crítico de desempenho
  • Implementando testes de fuzz para validação de entrada
  • Seguindo o fluxo de trabalho TDD em projetos Go

Fluxo de Trabalho TDD em Go

O Ciclo VERMELHO-VERDE-REFACTOR

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

TDD Passo a Passo em 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

Testes Orientados por Tabela

O padrão padrão para testes em Go. Permite cobertura abrangente com código mínimo.

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

Testes Orientados por Tabela com Casos de Erro

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

Subtestes e Sub-benchmarks

Organizando Testes Relacionados

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) {
        // ...
    })
}

Subtestes Paralelos

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

    for _, tt := range tests {

…
Perguntas frequentes

O que é TDD?

TDD significa Desenvolvimento Guiado por Testes. É uma prática onde você escreve um teste antes de escrever o código real. O teste ajuda a guiar o desenvolvimento e garante que o código funcione como esperado.

O que são 'table-driven tests'?

São uma forma organizada de escrever vários testes para a mesma função usando uma lista de casos de teste. Isso torna o código de teste mais limpo e fácil de gerenciar.

O que são 'benchmarks'?

Benchmarks são testes especiais que medem o desempenho do seu código. Eles ajudam a identificar partes lentas do seu programa para que você possa otimizá-las.

Detalhes

Descrição original do autor

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

Popularidade

Estrelas no GitHub
280 mil
Posição no ranking
#62
Licença
MIT
Atualizada em
15/10/2026

Essa skill é útil?

0

Entre para votar.

Comentários

  • …

Mais skills deste repositório

Skills parecidas