Testing a Collection of Functions with Reflection in Go
Problem
Unit testing a set of functions with similar signatures and return values can become repetitive and cumbersome. Traditional approaches involve writing individual tests for each function, which can lead to code duplication. Reflection offers a solution to streamline this process.
Solution Using Reflection
To leverage reflection in your tests:
Example Code
var funcNames = []string{"Func1", "Func2", "Func3"}
func TestFunc(t *testing.T) {
stype := reflect.ValueOf(s)
for _, fname := range funcNames {
fmt.Println(fname)
sfunc := stype.MethodByName(fname)
ret := sfunc.Call([]reflect.Value{})
val := ret[0].Int()
if val Note: If an invalid function name is specified, the test will panic. To mitigate this:
for _, fname := range funcNames {
defer func() {
if x := recover(); x != nil {
t.Error("TestFunc paniced for", fname, ": ", x)
}
}()
fmt.Println(fname)
}
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3