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.
Code
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
A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.CSS Unit ConverterConvert a length between px, rem, em, pt, pc, in, cm, mm, and percent using a configurable root font size, following the 96dpi CSS definition.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.JSONPath TesterTest JSONPath expressions against JSON documents with dot notation, brackets, wildcards, and recursive descent.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.