Table Tests, Subtests & Helpers | Go Tutorial #29
Video: Table Tests, Subtests & Helpers | Go Tutorial #29 by Taught by Celeste AI - AI Coding Coach
Watch full page →Table Tests, Subtests & Helpers in Go
Go’s built-in testing package provides powerful tools to write clear, maintainable unit tests without external dependencies. This tutorial covers essential patterns including table-driven tests, subtests, and helper functions to organize and simplify your test code effectively.
Code
package mymath
import (
"testing"
)
// Function to test
func Add(a, b int) int {
return a + b
}
// Test helper for error reporting
func checkSum(t *testing.T, got, want int) {
t.Helper() // Marks this function as a test helper
if got != want {
t.Errorf("Add() = %d; want %d", got, want)
}
}
// Table-driven test with subtests
func TestAdd(t *testing.T) {
tests := []struct {
name string
a, b int
want int
}{
{"both positive", 2, 3, 5},
{"positive and zero", 5, 0, 5},
{"negative and positive", -1, 1, 0},
{"both negative", -2, -3, -5},
}
for _, tc := range tests {
tc := tc // capture range variable
t.Run(tc.name, func(t *testing.T) {
got := Add(tc.a, tc.b)
checkSum(t, got, tc.want)
})
}
}
// Example of skipping a test conditionally
func TestSkipExample(t *testing.T) {
if testing.Short() {
t.Skip("Skipping test in short mode")
}
// test code here
}
// TestMain for setup and teardown
func TestMain(m *testing.M) {
// setup code here (e.g., initialize resources)
code := m.Run() // run tests
// teardown code here (e.g., clean up)
// exit with the test result code
// os.Exit(code)
}
Key Points
- Test functions must start with Test and accept *testing.T as a parameter.
- Table-driven tests use a slice of structs to run multiple cases cleanly and consistently.
- Subtests with t.Run() provide named, isolated test cases within a single test function.
- Use t.Helper() in helper functions to improve error reporting by skipping helper frames.
- TestMain allows setup and teardown logic around all tests in a package, and t.Skip() can conditionally skip tests.