In pursuit of 100% unit test coverage, we have several lines we're trying to test in one of our functions. The relevant function calls out to the runtime package:
// functionName returns a string representing the function name of the function n stack frames above the caller.
// if n = 0, the name of the function calling functionName() will be returned.
func functionName(n int) string {
pc, _, _, ok := runtime.Caller(n + 1)
if !ok {
return "unknown function"
}
me := runtime.FuncForPC(pc)
if me == nil {
return "unknown function"
}
split := strings.Split(me.Name(), ".")
if len(split) == 0 {
return "unknown function"
}
return split[len(split)-1]
}
Specifically, the 3 if
statements and their return values are currently untested, because the runtime functions don't appear to be easily manipulated to return the values we want. Our standard response in these cases is to mock out the items in question, but these calls are to package-level functions (rather than methods of an interface) within the runtime package itself.
My first thought was to mock out the runtime token itself by using a structure with Caller() and FuncForPC() methods, assigned to a variable named "runtime" in the test files (so it wouldn't affect the production code flow, since test files are omitted during normal builds). However, this triggers a build error about "runtime" being redeclared within the (global) block.
I know this would be possible if the "runtime" variable were declare in a non-global scope (example masking fmt), but I can't find an elegant way to do so such that it gets masked within the tests, but not within the production code itself. The only way I've thought of is by altering the source of the production code to declare such a variable and replacing it's value in the tests, but this is far from ideal, since it complicates the production code purely for the purposes of testing.
Any ideas?