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?