Go 1 · Code patterns

Table-driven test

Run many cases through one test function, each as a named subtest.

func TestAdd(t *testing.T) {
	tests := []struct {
		name     string
		a, b, want int
	}{
		{"positive", 1, 2, 3},
		{"zero", 0, 0, 0},
	}
	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			if got := Add(tc.a, tc.b); got != tc.want {
				t.Errorf("got %d, want %d", got, tc.want)
			}
		})
	}
}

Official Go 1 documentation

More code patterns commands

All code patterns commands · Go 1 cheatsheet

Was this page helpful?