🧪 Cap 18: Testes Automatizados: Pacote testing, Table-Driven Tests, Benchmarks e Coverage - Exemplos Práticos
Código executável completo demonstrando os conceitos abordados em Go.
🗺️ Fluxo de Execução
flowchart TD
TEST["Testes em Go: go test -v -cover"]
TEST --> TABLE["Table-Driven Tests: Slice de structs com casos de teste"]
TEST --> BENCH["Benchmarks (testing.B): Mede nanosegundos por operação (ns/op)"]
style TEST fill:#e1f5fe,stroke:#03a9f4,stroke-width:2px
style TABLE fill:#e8f5e9,stroke:#4caf50,stroke-width:2px
📄 Código de Demonstração (math_test.go)
package main
import "testing"
func Somar(a, b int) int {
\return a + b
}
func TestSomarTableDriven(t *testing.T) {
\testes := []struct {
\nome string
\a, b int
\esperado int
}{
{"positivos", 2, 3, 5},
{"negativos", -1, -2, -3},
{"com zero", 0, 10, 10},
}
\for _, tt := range testes {
\t.Run(tt.nome, func(t *testing.T) {
\if res := Somar(tt.a, tt.b); res != tt.esperado {
\t.Errorf("obtido %d, esperado %d", res, tt.esperado)
}
})
}
}
🚀 Saída Esperada no Terminal
$ go test -v
=== RUN TestSomarTableDriven
=== RUN TestSomarTableDriven/positivos
=== RUN TestSomarTableDriven/negativos
=== RUN TestSomarTableDriven/com_zero
--- PASS: TestSomarTableDriven (0.00s)
PASS
ok portal/sistemas 0.015s
🧭 Navegação Rápida
| 📖 Teoria | 📊 Slides | 🧠 Quiz | 💻 Exemplos | 🧩 Exercícios | | :— | :— | :— | :— | :— | | Ler Tópico | Ver Slides | Fazer Quiz | Ver Código | Praticar |