Table-Driven Unit Test in Go

Structure Go tests as a table of cases with subtests, so each scenario is named, isolated, and easy to extend with new rows.

GoData Integrity

Code

gosnippet
31 lines
package calc

import "testing"

func Divide(a, b float64) (float64, bool) {
	if b == 0 {
		return 0, false
	}
	return a / b, true
}

func TestDivide(t *testing.T) {
	cases := []struct {
		name    string
		a, b    float64
		want    float64
		wantOK  bool
	}{
		{name: "even", a: 10, b: 2, want: 5, wantOK: true},
		{name: "fraction", a: 1, b: 4, want: 0.25, wantOK: true},
		{name: "divide by zero", a: 1, b: 0, want: 0, wantOK: false},
	}
	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			got, ok := Divide(tc.a, tc.b)
			if ok != tc.wantOK || got != tc.want {
				t.Fatalf("got (%v, %v), want (%v, %v)", got, ok, tc.want, tc.wantOK)
			}
		})
	}
}

What the code does

Table-Driven Unit Test in Go keeps everything in the functions Divide and TestDivide.

Repetition is confined to for _, tc := range cases — the rest of the file is straight-line.

Applying it

Entry signature: func Divide(a, b float64) (float64, bool)

Divide is what another module would consume; nothing else here is load-bearing for callers.

Statements that matter

func Divide(a, b float64) (float64, bool) {
	if b == 0 {
		return 0, false
	}
	return a / b, true
}
for _, tc := range cases {
	t.Run(tc.name, func(t *testing.T) {
		got, ok := Divide(tc.a, tc.b)
		if ok != tc.wantOK || got != tc.want {
			t.Fatalf("got (%v, %v), want (%v, %v)", got, ok, tc.want, tc.wantOK)
		}
	})
}

Interactive Tools for This Topic

FAQ

Will the snippet run without installing packages?
Yes, it runs as-is — nothing outside the built-in APIs is referenced. Every import resolves inside the standard library — `testing`. The file defines `Divide`, `TestDivide` at load time.