File _test.go, function TestXxx(t *testing.T).
- Run:
go test ./.... - Go không có built-in assert — dùng if/t.Errorf.
- Table-driven tests là pattern phổ biến.
go
// math_test.go
package math
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)
}
}
// Table-driven test
func TestMultiply(t *testing.T) {
tests := []struct {
name string
a, b int
want int
}{
{"positive", 3, 4, 12},
{"zero", 0, 5, 0},
{"negative", -2, 3, -6},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := Multiply(tt.a, tt.b)
if got != tt.want {
t.Errorf("Multiply(%d, %d) = %d; want %d", tt.a, tt.b, got, tt.want)
}
})
}
}