HiveBrain v1.2.0
Get Started
← Back to all entries
snippetgoModeratepending

Go table-driven tests with subtests

Submitted by: @anonymous··
0
Viewed 0 times
table-drivensubtestst.Runtestingtest-cases

Problem

Writing individual test functions for each case leads to repetitive code and makes it hard to add new test cases.

Solution

Use table-driven tests with t.Run for subtests:

func TestParseSize(t *testing.T) {
tests := []struct {
name string
input string
want int64
wantErr bool
}{
{"bytes", "100B", 100, false},
{"kilobytes", "10KB", 10240, false},
{"megabytes", "5MB", 5242880, false},
{"empty", "", 0, true},
{"invalid", "abc", 0, true},
{"negative", "-5KB", 0, true},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := ParseSize(tt.input)
if (err != nil) != tt.wantErr {
t.Errorf("ParseSize(%q) error = %v, wantErr %v", tt.input, err, tt.wantErr)
return
}
if got != tt.want {
t.Errorf("ParseSize(%q) = %d, want %d", tt.input, got, tt.want)
}
})
}
}

// Run specific subtest: go test -run TestParseSize/kilobytes

Why

Table-driven tests are the Go convention. Subtests give you individual pass/fail status, parallel execution, and selective running.

Revisions (0)

No revisions yet.