| 1 |
# Testing Generic Functions with Table-Driven Tests |
| 2 |
|
| 3 |
## The Challenge |
| 4 |
|
| 5 |
Go generics require type parameters to be resolved at compile time. This creates a problem for traditional table-driven tests where test cases are stored in a slice of `any`: |
| 6 |
|
| 7 |
```go |
| 8 |
// This DOES NOT work - type parameter cannot be inferred from 'any' |
| 9 |
cases := []struct { |
| 10 |
name string |
| 11 |
value1 any |
| 12 |
value2 any |
| 13 |
}{ |
| 14 |
{"int", 1, 2}, |
| 15 |
{"string", "a", "b"}, |
| 16 |
} |
| 17 |
|
| 18 |
for _, c := range cases { |
| 19 |
GreaterT(mock, c.value1, c.value2) // Error: cannot infer type parameter |
| 20 |
} |
| 21 |
``` |
| 22 |
|
| 23 |
## The Solution: Test Function Closures |
| 24 |
|
| 25 |
Wrap each test case in a closure where the type parameter is resolved at slice construction time, not iteration time. |
| 26 |
|
| 27 |
### Step 1: Define a Test Case Struct |
| 28 |
|
| 29 |
```go |
| 30 |
import "testing" |
| 31 |
|
| 32 |
// genericTestCase wraps a test function with its name for table-driven tests. |
| 33 |
type genericTestCase struct { |
| 34 |
name string |
| 35 |
test func(*testing.T) |
| 36 |
} |
| 37 |
``` |
| 38 |
|
| 39 |
### Step 2: Create a Generic Test Helper |
| 40 |
|
| 41 |
The helper function is generic and returns a closure. The type parameter is resolved when the closure is created (at slice construction), not when it's executed. |
| 42 |
|
| 43 |
```go |
| 44 |
import "testing" |
| 45 |
|
| 46 |
// testGreaterT creates a test function for GreaterT with specific type V. |
| 47 |
// Type parameter V is resolved when this function is called, not when the |
| 48 |
// returned closure executes. |
| 49 |
func testGreaterT[V Ordered](successE1, successE2, failE1, failE2 V) func(*testing.T) { |
| 50 |
return func(t *testing.T) { |
| 51 |
t.Parallel() |
| 52 |
mock := new(mockT) |
| 53 |
|
| 54 |
// Success case: e1 > e2 |
| 55 |
True(t, GreaterT(mock, successE1, successE2)) |
| 56 |
|
| 57 |
// Failure case: e1 <= e2 |
| 58 |
False(t, GreaterT(mock, failE1, failE2)) |
| 59 |
|
| 60 |
// Equal values should fail |
| 61 |
False(t, GreaterT(mock, successE1, successE1)) |
| 62 |
} |
| 63 |
} |
| 64 |
``` |
| 65 |
|
| 66 |
### Step 3: Create Iterator Function for Test Cases |
| 67 |
|
| 68 |
Use the iterator pattern (`iter.Seq`) to return test cases: |
| 69 |
|
| 70 |
```go |
| 71 |
import ( |
| 72 |
"iter" |
| 73 |
"slices" |
| 74 |
) |
| 75 |
|
| 76 |
func greaterTCases() iter.Seq[genericTestCase] { |
| 77 |
return slices.Values([]genericTestCase{ |
| 78 |
// Numeric types - type inferred from arguments |
| 79 |
{"int", testGreaterT[int](2, 1, 1, 2)}, |
| 80 |
{"int8", testGreaterT[int8](2, 1, 1, 2)}, |
| 81 |
{"int16", testGreaterT[int16](2, 1, 1, 2)}, |
| 82 |
{"int32", testGreaterT[int32](2, 1, 1, 2)}, |
| 83 |
{"int64", testGreaterT[int64](2, 1, 1, 2)}, |
| 84 |
{"uint", testGreaterT[uint](2, 1, 1, 2)}, |
| 85 |
{"uint8", testGreaterT[uint8](2, 1, 1, 2)}, |
| 86 |
{"uint16", testGreaterT[uint16](2, 1, 1, 2)}, |
| 87 |
{"uint32", testGreaterT[uint32](2, 1, 1, 2)}, |
| 88 |
{"uint64", testGreaterT[uint64](2, 1, 1, 2)}, |
| 89 |
{"uintptr", testGreaterT[uintptr](2, 1, 1, 2)}, |
| 90 |
{"float32", testGreaterT[float32](2.0, 1.0, 1.0, 2.0)}, |
| 91 |
{"float64", testGreaterT[float64](2.0, 1.0, 1.0, 2.0)}, |
| 92 |
{"string", testGreaterT[string]("b", "a", "a", "b")}, |
| 93 |
|
| 94 |
// Special types requiring dedicated setup functions |
| 95 |
{"time.Time", testGreaterTTime()}, |
| 96 |
{"[]byte", testGreaterTBytes()}, |
| 97 |
|
| 98 |
// Custom types to verify constraint satisfaction |
| 99 |
{"custom int type", testGreaterTCustomInt()}, |
| 100 |
}) |
| 101 |
} |
| 102 |
``` |
| 103 |
|
| 104 |
### Step 4: Handle Special Types |
| 105 |
|
| 106 |
Some types need dedicated test functions because they require specific setup: |
| 107 |
|
| 108 |
```go |
| 109 |
import ( |
| 110 |
"testing" |
| 111 |
"time" |
| 112 |
) |
| 113 |
|
| 114 |
// testGreaterTTime tests GreaterT with time.Time values. |
| 115 |
func testGreaterTTime() func(*testing.T) { |
| 116 |
return func(t *testing.T) { |
| 117 |
t.Parallel() |
| 118 |
mock := new(mockT) |
| 119 |
|
| 120 |
t0 := time.Now() |
| 121 |
t1 := t0.Add(-time.Second) // t1 is before t0 |
| 122 |
|
| 123 |
True(t, GreaterT(mock, t0, t1)) // t0 > t1 |
| 124 |
False(t, GreaterT(mock, t1, t0)) // t1 < t0 |
| 125 |
False(t, GreaterT(mock, t0, t0)) // equal |
| 126 |
} |
| 127 |
} |
| 128 |
|
| 129 |
// testGreaterTBytes tests GreaterT with []byte values. |
| 130 |
func testGreaterTBytes() func(*testing.T) { |
| 131 |
return func(t *testing.T) { |
| 132 |
t.Parallel() |
| 133 |
mock := new(mockT) |
| 134 |
|
| 135 |
b1 := []byte("b") |
| 136 |
b2 := []byte("a") |
| 137 |
|
| 138 |
True(t, GreaterT(mock, b1, b2)) |
| 139 |
False(t, GreaterT(mock, b2, b1)) |
| 140 |
False(t, GreaterT(mock, b1, b1)) |
| 141 |
} |
| 142 |
} |
| 143 |
|
| 144 |
// testGreaterTCustomInt verifies custom types satisfying the constraint work. |
| 145 |
type myInt int |
| 146 |
|
| 147 |
func testGreaterTCustomInt() func(*testing.T) { |
| 148 |
return func(t *testing.T) { |
| 149 |
t.Parallel() |
| 150 |
mock := new(mockT) |
| 151 |
|
| 152 |
True(t, GreaterT(mock, myInt(2), myInt(1))) |
| 153 |
False(t, GreaterT(mock, myInt(1), myInt(2))) |
| 154 |
} |
| 155 |
} |
| 156 |
``` |
| 157 |
|
| 158 |
### Step 5: Write the Test Function |
| 159 |
|
| 160 |
```go |
| 161 |
import "testing" |
| 162 |
|
| 163 |
func TestCompareGreaterT(t *testing.T) { |
| 164 |
t.Parallel() |
| 165 |
|
| 166 |
for tc := range greaterTCases() { |
| 167 |
t.Run(tc.name, tc.test) |
| 168 |
} |
| 169 |
} |
| 170 |
``` |
| 171 |
|
| 172 |
## Complete Pattern Summary |
| 173 |
|
| 174 |
```go |
| 175 |
import ( |
| 176 |
"iter" |
| 177 |
"slices" |
| 178 |
"testing" |
| 179 |
) |
| 180 |
|
| 181 |
// 1. Test case wrapper struct |
| 182 |
type genericTestCase struct { |
| 183 |
name string |
| 184 |
test func(*testing.T) |
| 185 |
} |
| 186 |
|
| 187 |
// 2. Generic test helper returning closure |
| 188 |
func testFunctionUnderTest[V Constraint](args V) func(*testing.T) { |
| 189 |
return func(t *testing.T) { |
| 190 |
t.Parallel() |
| 191 |
// Test logic using args with type V |
| 192 |
} |
| 193 |
} |
| 194 |
|
| 195 |
// 3. Special type handlers |
| 196 |
func testFunctionUnderTestSpecialType() func(*testing.T) { |
| 197 |
return func(t *testing.T) { |
| 198 |
t.Parallel() |
| 199 |
// Test logic with special setup |
| 200 |
} |
| 201 |
} |
| 202 |
|
| 203 |
// 4. Iterator function |
| 204 |
func functionUnderTestCases() iter.Seq[genericTestCase] { |
| 205 |
return slices.Values([]genericTestCase{ |
| 206 |
{"type1", testFunctionUnderTest[Type1](value1)}, |
| 207 |
{"type2", testFunctionUnderTest[Type2](value2)}, |
| 208 |
{"special", testFunctionUnderTestSpecialType()}, |
| 209 |
}) |
| 210 |
} |
| 211 |
|
| 212 |
// 5. Test function |
| 213 |
func TestFunctionUnderTest(t *testing.T) { |
| 214 |
t.Parallel() |
| 215 |
for tc := range functionUnderTestCases() { |
| 216 |
t.Run(tc.name, tc.test) |
| 217 |
} |
| 218 |
} |
| 219 |
``` |
| 220 |
|
| 221 |
## Key Insights |
| 222 |
|
| 223 |
1. **Type resolution timing**: Generic type parameters are resolved at compile time. By creating closures at slice construction, each closure has its type parameter already resolved. |
| 224 |
|
| 225 |
2. **Closure captures**: The generic test helper captures the typed arguments in its closure, preserving type information for when the test executes. |
| 226 |
|
| 227 |
3. **Special type handling**: Types like `time.Time` and `[]byte` need dedicated functions because they require specific construction patterns that don't fit the simple value pattern. |
| 228 |
|
| 229 |
4. **Custom type testing**: Always include at least one custom type (e.g., `type myInt int`) to verify the constraint works with user-defined types, not just built-in types. |
| 230 |
|
| 231 |
5. **Parallel execution**: Each closure is independent, enabling parallel test execution with `t.Parallel()`. |
| 232 |
|
| 233 |
## When to Use This Pattern |
| 234 |
|
| 235 |
- Testing generic functions with type constraints |
| 236 |
- When you need to verify behavior across multiple types satisfying a constraint |
| 237 |
- When traditional table-driven tests fail due to type inference limitations |
| 238 |
- Testing functions from `internal/assertions/` that have generic variants (e.g., `GreaterT`, `LessT`, `PositiveT`) |