go-testing-subtests
Subtest patterns with t.Run
When & Why to Use This Skill
This Claude skill provides expert guidance on implementing subtests in Go using the t.Run pattern. It focuses on logical grouping of related test cases, improving test output hierarchy, and enabling selective execution of specific scenarios to streamline the Go development and debugging workflow. By adopting these patterns, developers can create more maintainable, readable, and efficient unit tests in Golang.
Use Cases
- Grouping multiple validation scenarios (such as valid, invalid, and edge cases) for a single function to maintain a clean and organized test suite.
- Isolating and debugging specific test failures by running individual subtests from the command line using the -run flag without executing the entire suite.
- Improving test reporting and code review clarity by transforming flat, repetitive test functions into a structured hierarchy that clearly defines relationships between test cases.
| name | go-testing-subtests |
|---|---|
| description | Subtest patterns with t.Run |
Subtests with t.Run
Use t.Run to group related tests and enable selective execution.
CORRECT
func Test_User_Validation(t *testing.T) {
t.Run("valid email", func(t *testing.T) {
user := User{Email: "test@example.com"}
if err := user.Validate(); err != nil {
t.Errorf("expected valid, got error: %v", err)
}
})
t.Run("invalid email", func(t *testing.T) {
user := User{Email: "invalid"}
if err := user.Validate(); err == nil {
t.Error("expected error, got nil")
}
})
t.Run("empty email", func(t *testing.T) {
user := User{Email: ""}
if err := user.Validate(); err == nil {
t.Error("expected error, got nil")
}
})
}
Run specific subtest:
go test -run Test_User_Validation/invalid_email
Why:
- Logical grouping of related tests
- Can run subtests individually
- Clean test output with hierarchy
- Failures don't stop other subtests
WRONG
func Test_User_ValidEmail(t *testing.T) { /* ... */ }
func Test_User_InvalidEmail(t *testing.T) { /* ... */ }
func Test_User_EmptyEmail(t *testing.T) { /* ... */ }
Problems:
- No grouping relationship
- Harder to run related tests together
- More verbose test names