Knowledge
Search knowledge... ⌘K
Knowledge · Guidelines · go
Table Driven Tests
How to write table-driven tests for Go packages
Metadata
go go recommended
Procedures
Showing 3 of 4
- 1 Identify test cases from package exports
Read package.yml exports to identify functions that need tests
# From package.yml exports: # - ValidateConfig # - ParseConnectionString # Each export = at least one test function
- 2 Create test struct with descriptive fields
Use named fields, not positional. Include name, input, expected output, and wantErr
tests := []struct { name string input Config want bool wantErr bool }{ {name: "valid config", input: validConfig, want: true}, {name: "empty host", input: Config{Host: ""}, wantErr: true}, } - 3 Run subtests with t.Run
Each test case runs as a named subtest for clear failure reporting
for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := ValidateConfig(tt.input) if (err != nil) != tt.wantErr { t.Errorf("error = %v, wantErr %v", err, tt.wantErr) return } if got != tt.want { t.Errorf("got %v, want %v", got, tt.want) } }) }
Tools
- Go test
- Go test coverage
References
- external Go Wiki Table Driven Tests