We were brainstorming possible ways of testing generic functions using table driven tests. It seems pretty complicated at the first glance.
What we wanted to achieve is to have a field in the test table struct that can be of whatever type that is accepted by the generic function. It seems however, that you can't use any interface for that.
We came up with the following solution:
Example function:
func PtrTo[T any](t T) *T {
return &t
}
Example test:
func TestPtrTo(t *testing.T) {
string1 := "abcd"
trueVar := true
testCases := []struct {
testDescription string
input interface{}
expectedOutput interface{}
}{
{
testDescription: "string",
input: string1,
expectedOutput: &string1,
},
{
testDescription: "bool",
input: trueVar,
expectedOutput: &trueVar,
},
}
for _, testCase := range testCases {
t.Run(testCase.testDescription, func(t *testing.T) {
switch concreteTypeInput := testCase.input.(type) {
case string:
output := PtrTo(concreteTypeInput)
assert.Equal(t, testCase.expectedOutput, output)
case bool:
output := PtrTo(concreteTypeInput)
assert.Equal(t, testCase.expectedOutput, output)
default:
t.Error("Unexpected type. Please add the type to the switch case")
}
})
}
}
It doesn't really feel optimal, though.
What do you think of this solution?
Do you see any other alternatives?
It doesn't make sense to table-test generics the way you describe.
The code is generic: if it compiles in the first place, then you have the compile-time guarantee that it will behave exactly the same for all values of
Tthat satisfy the constraint(s).In other words, it's pointless to test that the return type of
PtrTois*boolwhenTisbool. The compiler already type-checked it for you.It makes sense to test different input types only if:
Tis constrained by a union and the function body makes use of operators that have different semantics based on the type, e.g.+operator with number types (sum) or with string types (concatenation)When you have broad constraints like
anyand the semantics of the function body are the same for allTs, just test it with a random type and call it a day.