I have to write unit tests for several functions with similar signature and return values (an object and an error), which must pass similar test conditions.
I would like to avoid writing:
func TestFunc1(t *testing.T) {
// tests on return values
}
func TestFunc2(t *testing.T) {
// tests identical for Func1
}
func TestFunc3(t *testing.T) {
// tests identical for Func1
}
...
(See this go playground example for a more complete context)
(yes, go playground doesn't support yet go test
, only go run
, and issue 6511 is there to request that feature)
How would you use reflection (reflect
package) in order to write only one test which would:
- call each function in turn?
- test their return value?
I have seen:
- "How to properly use
.Call
in reflect package, Golang?", using Value.Call - "Selecting a function from a list of functions in Golang"
But I miss a complete example for calling functions and using the returned values in a test.
Once I understood that everything must use or return the type Value, here is what I came up with.
The trick is to use:
ValueOf
in order to get a value of the receiverValue.MethodByName
to find a function of that receiver valueValue.IsNil
to test fornil
returned value.Main extract of the test code:
See a runnable example in go playground.
Note that if you are calling that test function with a non-existent function name, that will panic.
See that example here.
Go playground recover from that panic, but your test program might not.
That is why I added to the test function above:
That produces (see example) a much nicer output: