Trung BìnhGolang iconGolang

Table-driven tests trong Go là gì?

Pattern test nhiều cases bằng slice of structs — DRY, dễ thêm cases, idiomatic Go.

go
func TestSquare(t *testing.T) {
    cases := []struct {
        name  string
        input int
        want  int
    }{
        {"positive", 5, 25},
        {"zero", 0, 0},
        {"negative", -3, 9},
    }
    for _, tc := range cases {
        t.Run(tc.name, func(t *testing.T) {
            got := Square(tc.input)
            if got != tc.want {
                t.Errorf("Square(%d) = %d; want %d", tc.input, got, tc.want)
            }
        })
    }
}

Mỗi sub-test chạy độc lập với t.Run, có thể filter: go test -run TestSquare/positive.

Xem toàn bộ Golang cùng filter theo level & chủ đề con.

Mở danh sách Golang