Padrões de Teste em Go
Padrões abrangentes de teste em Go para escrever testes confiáveis e de fácil manutenção 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 fuzzing para validação de entrada
- Seguindo o fluxo de trabalho TDD em projetos Go
Fluxo de Trabalho TDD para Go
O Ciclo RED-GREEN-REFACTOR
RED → Escreva um teste com falha primeiro
GREEN → Escreva o mínimo de código para passar no teste
REFACTOR → Melhore o código mantendo os testes verdes
REPEAT → Continue com o próximo requisito
TDD Passo a Passo em Go
// Passo 1: Defina a interface/assinatura
// calculator.go
package calculator
func Add(a, b int) int {
panic("não implementado") // Placeholder
}
// Passo 2: Escreva o teste com falha (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)
}
}
// Passo 3: Execute o teste - verifique FALHA
// $ go test
// --- FAIL: TestAdd (0.00s)
// panic: não implementado
// Passo 4: Implemente o código mínimo (GREEN)
func Add(a, b int) int {
return a + b
}
// Passo 5: Execute o teste - verifique PASS
// $ go test
// PASS
// Passo 6: Refatore se necessário, verifique se os testes ainda passam
Testes Guiados 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
}{
{"números positivos", 2, 3, 5},
{"números negativos", -1, -2, -3},
{"valores zero", 0, 0, 0},
{"sinais mistos", -1, 1, 0},
{"números grandes", 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 Guiados por Tabela com Casos de Erro
func TestParseConfig(t *testing.T) {
tests := []struct {
name string
input string
want *Config
wantErr bool
}{
{
name: "config válido",
input: `{"host": "localhost", "port": 8080}`,
want: &Config{Host: "localhost", Port: 8080},
},
{
name: "JSON inválido",
input: `{inválido}`,
wantErr: true,
},
{
name: "entrada vazia",
input: "",
wantErr: true,
},
{
name: "config mínimo",
input: `{}`,
want: &Config{}, // Configuração de valor zero
},
}
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("erro esperado, obteve nil")
}
return
}
if err != nil {
t.Fatalf("erro inesperado: %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) {
// Configuração compartilhada por todos os subtestes
db := setupTestDB(t)
t.Run("Create", func(t *testing.T) {
user := &User{Name: "Alice"}
err := db.CreateUser(user)
if err != nil {
t.Fatalf("CreateUser falhou: %v", err)
}
if user.ID == "" {
t.Error("ID do usuário esperado")
}
})
t.Run("Get", func(t *testing.T) {
user, err := db.GetUser("alice-id")
if err != nil {
t.Fatalf("GetUser falhou: %v", err)
}
if user.Name != "Alice" {
t.Errorf("obteve nome %q; esperado %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
}{
{"caso1", "entrada1"},
{"caso2", "entrada2"},
{"caso3", "entrada3"},
}
for _, tt := range tests {
tt := tt // Capturar variável de iteração
t.Run(tt.name, func(t *testing.T) {
t.Parallel() // Executar subtestes em paralelo
result := Process(tt.input)
// asserções...
_ = result
})
}
}
Helpers de Teste
Funções Helper
func setupTestDB(t *testing.T) *sql.DB {
t.Helper() // Marca esta como uma função helper
db, err := sql.Open("sqlite3", ":memory:")
if err != nil {
t.Fatalf("falha ao abrir banco de dados: %v", err)
}
// Limpeza quando o teste terminar
t.Cleanup(func() {
db.Close()
})
// Executar migrações
if _, err := db.Exec(schema); err != nil {
t.Fatalf("falha ao criar esquema: %v", err)
}
return db
}
func assertNoError(t *testing.T, err error) {
t.Helper()
if err != nil {
t.Fatalf("erro inesperado: %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)
}
}
Arquivos e Diretórios Temporários
func TestFileProcessing(t *testing.T) {
// Criar diretório temporário - limpo automaticamente
tmpDir := t.TempDir()
// Criar arquivo de teste
testFile := filepath.Join(tmpDir, "test.txt")
err := os.WriteFile(testFile, []byte("conteúdo de teste"), 0644)
if err != nil {
t.Fatalf("falha ao criar arquivo de teste: %v", err)
}
// Executar teste
result, err := ProcessFile(testFile)
if err != nil {
t.Fatalf("ProcessFile falhou: %v", err)
}
// Asserção...
_ = result
}
Arquivos Golden
Testes contra arquivos de saída esperados armazenados em testdata/.
var update = flag.Bool("update", false, "atualizar arquivos golden")
func TestRender(t *testing.T) {
tests := []struct {
name string
input Template
}{
{"simples", Template{Name: "teste"}},
{"complexo", Template{Name: "teste", 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 {
// Atualizar arquivo golden: go test -update
err := os.WriteFile(golden, got, 0644)
if err != nil {
t.Fatalf("falha ao atualizar arquivo golden: %v", err)
}
}
want, err := os.ReadFile(golden)
if err != nil {
t.Fatalf("falha ao ler arquivo golden: %v", err)
}
if !bytes.Equal(got, want) {
t.Errorf("incompatibilidade de saída:\ngot:\n%s\nwant:\n%s", got, want)
}
})
}
}
Mocking com Interfaces
Mocking Baseado em Interface
// Definir interface para dependências
type UserRepository interface {
GetUser(id string) (*User, error)
SaveUser(user *User) error
}
// Implementação de produção
type PostgresUserRepository struct {
db *sql.DB
}
func (r *PostgresUserRepository) GetUser(id string) (*User, error) {
// Consulta real ao banco de dados
}
// Implementação Mock para testes
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)
}
// Teste usando 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("erro inesperado: %v", err)
}
if user.Name != "Alice" {
t.Errorf("obteve nome %q; esperado %q", user.Name, "Alice")
}
}
Benchmarks
Benchmarks Básicos
func BenchmarkProcess(b *testing.B) {
data := generateTestData(1000)
b.ResetTimer() // Não conta o tempo de configuração
for i := 0; i < b.N; i++ {
Process(data)
}
}
// Execute: go test -bench=BenchmarkProcess -benchmem
// Saída: BenchmarkProcess-8 10000 105234 ns/op 4096 B/op 10 allocs/op
Benchmark com Diferentes Tamanhos
func BenchmarkSort(b *testing.B) {
sizes := []int{100, 1000, 10000, 100000}
for _, size := range sizes {
b.Run(fmt.Sprintf("tamanho=%d", size), func(b *testing.B) {
data := generateRandomSlice(size)
b.ResetTimer()
for i := 0; i < b.N; i++ {
// Fazer uma cópia para evitar ordenar dados já ordenados
tmp := make([]int, len(data))
copy(tmp, data)
sort.Ints(tmp)
}
})
}
}
Benchmarks de Alocação de Memória
func BenchmarkStringConcat(b *testing.B) {
parts := []string{"hello", "world", "foo", "bar", "baz"}
b.Run("mais", 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, "")
}
})
}
Fuzzing (Go 1.18+)
Teste de Fuzzing Básico
func FuzzParseJSON(f *testing.F) {
// Adicionar corpus de sementes
f.Add(`{"name": "teste"}`)
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 inválido é esperado para entrada aleatória
return
}
// Se o parsing foi bem-sucedido, a re-codificação deve funcionar
_, err = json.Marshal(result)
if err != nil {
t.Errorf("Marshal falhou após Unmarshal bem-sucedido: %v", err)
}
})
}
// Execute: go test -fuzz=FuzzParseJSON -fuzztime=30s
Teste de Fuzzing com Múltiplas Entradas
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)
// Propriedade: Compare(a, a) deve sempre ser igual a 0
if a == b && result != 0 {
t.Errorf("Compare(%q, %q) = %d; want 0", a, b, result)
}
// Propriedade: Compare(a, b) e Compare(b, a) devem ter sinais opostos
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; inconsistente",
a, b, result, b, a, reverse)
}
}
})
}
Cobertura de Teste
Executando Cobertura
# Cobertura básica
go test -cover ./...
# Gerar perfil de cobertura
go test -coverprofile=coverage.out ./...
# Visualizar cobertura no navegador
go tool cover -html=coverage.out
# Visualizar cobertura por função
go tool cover -func=coverage.out
# Cobertura com detecção de condição de corrida
go test -race -coverprofile=coverage.out ./...
Metas de Cobertura
| Tipo de Código | Meta |
|---|---|
| Lógica de negócios crítica | 100% |
| APIs públicas | 90%+ |
| Código geral | 80%+ |
| Código gerado | Excluir |
Excluindo Código Gerado da Cobertura
//go:generate mockgen -source=interface.go -destination=mock_interface.go
// No perfil de cobertura, exclua com tags de compilação:
// go test -cover -tags=!generate ./...
Teste de Handler HTTP
func TestHealthHandler(t *testing.T) {
// Criar requisição
req := httptest.NewRequest(http.MethodGet, "/health", nil)
w := httptest.NewRecorder()
// Chamar handler
HealthHandler(w, req)
// Verificar resposta
resp := w.Result()
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Errorf("obteve status %d; esperado %d", resp.StatusCode, http.StatusOK)
}
body, _ := io.ReadAll(resp.Body)
if string(body) != "OK" {
t.Errorf("obteve corpo %q; esperado %q", body, "OK")
}
}
func TestAPIHandler(t *testing.T) {
tests := []struct {
name string
method string
path string
body string
wantStatus int
wantBody string
}{
{
name: "obter usuário",
method: http.MethodGet,
path: "/users/123",
wantStatus: http.StatusOK,
wantBody: `{"id":"123","name":"Alice"}`,
},
{
name: "não encontrado",
method: http.MethodGet,
path: "/users/999",
wantStatus: http.StatusNotFound,
},
{
name: "criar usuário",
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) {
// Construir requisição
var req *http.Request
if tt.body != "" {
req = httptest.NewRequest(tt.method, tt.path, strings.NewReader(tt.body))
req.Header.Set("Content-Type", "application/json")
} else {
req = httptest.NewRequest(tt.method, tt.path, nil)
}
w := httptest.NewRecorder()
handler.ServeHTTP(w, req)
resp := w.Result()
defer resp.Body.Close()
// Verificar status code
if resp.StatusCode != tt.wantStatus {
t.Errorf("obteve status %d; esperado %d", resp.StatusCode, tt.wantStatus)
}
// Verificar corpo se esperado
if tt.wantBody != "" {
body, _ := io.ReadAll(resp.Body)
if string(body) != tt.wantBody {
t.Errorf("obteve corpo %q; esperado %q", body, tt.wantBody)
}
}
})
}
}