Skip to content

Instantly share code, notes, and snippets.

@micahhausler
Created February 10, 2023 16:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save micahhausler/c535ae54d5f9a02412ac85f5d8e21ba6 to your computer and use it in GitHub Desktop.
Save micahhausler/c535ae54d5f9a02412ac85f5d8e21ba6 to your computer and use it in GitHub Desktop.
Reflective Go Test Runner
package tests
import (
"reflect"
"strings"
"testing"
)
type TestRunner struct{}
func (tr *TestRunner) Runtests() {
testSuite := []testing.InternalTest{}
// Dynamically find methods matching `Test*(*testing.T)`
typ := reflect.TypeOf(tr)
val := reflect.ValueOf(tr)
for i := 0; i < typ.NumMethod(); i++ {
method := typ.Method(i)
twoIn := method.Type.NumIn() == 2
zeroOut := method.Type.NumOut() == 0
testingArg := method.Type.In(1).String() == "*testing.T"
testPrefix := strings.HasPrefix(method.Name, "Test")
if twoIn && zeroOut && testingArg && testPrefix {
methodVal := val.MethodByName(method.Name)
methodIface := methodVal.Convert(reflect.TypeOf((*func(*testing.T))(nil)).Elem()).Interface()
if methodFunc, ok := methodIface.(func(*testing.T)); ok {
testSuite = append(testSuite, testing.InternalTest{Name: method.Name, F: methodFunc})
}
}
}
testing.Main(matchString, testSuite, nil, nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment