I'm trying to test a function that accepts a parameter of the type "error". The function should panic under certain situations and I'm trying to test scenarios.
However, when I try to use reflect.Call
on a nil
value (which can be passed into a function that accepts something of type "error"), it seems to result in a panic with the following message:
reflect: Call using zero Value argument
I have found the following posts but I am failing to integrate it into my function.
Relevant Go Playground: http://play.golang.org/p/cYQMQ6amPH
In the playground above, I would like the call to InvocationCausedPanic(PanicOnErr, nil)
to return false
, however, the above panic from reflect is causing a false positive.
Are there any modifications I can make to the InvocationCausedPanic
or the invoke
functions to make this work (while retaining its ability to test other functions that cannot accept nil
as an argument - a function that accepts a string for instance)?
Perhaps the issue is in how the function is called?
I've tred things like InvocationCausedPanic(PanicOnErr, new(error))
or InvocationCausedPanic(PanicOnErr, error(nil))
to no avail.
Thanks for any advice.
If the parameter value is nil, then use a zero value of the function parameter type.
if paramValue == nil {
reflectedParams[paramIndex] = reflect.New(expectedType).Elem()
} else {
reflectedParams[paramIndex] = reflect.ValueOf(paramValue)
}
You can simplify the code if you compute the reflect value and then check assignability. With this change, the compatible
function is not required.
for paramIndex, paramValue := range params {
if paramValue == nil {
reflectedParams[paramIndex] = reflect.New(expectedType).Elem()
} else {
reflectedParams[paramIndex] = reflect.ValueOf(paramValue)
}
expectedType := funcType.In(paramIndex)
actualType := reflectedParams[paramIndex].Type()
if !actualType.AssignableTo(expectedType) {
errStr := fmt.Sprintf("InvocationCausedPanic called with a mismatched parameter type [parameter #%v: expected %v; got %v].", paramIndex, expectedType,actualType)
panic(errStr)
}
}