How would you write a test for a function that returns a value that could either be nil or a concrete value? I don't care about the actual value itself, I just care about whether the value has been returned or not.
type CustomType struct{}
func TestSomeFunc(t *testing.T) {
case := map[string]struct {
Input string
Expected *CustomType // expected result
Error error // expected error value
} {
"test case 1":
"input",
&CustomType{}, // could be nil or a concrete value
nil,
"test case 2":
"input",
nil, // could be nil or a concrete value
ErrSomeError,
}
actual, err := SomeFunc(case.Input)
if (actual != case.Expected) {
t.Fatalf(...)
}
}
and the function to be tested could look something like:
func SomeFunc(input string) (*CustomType, error) {
foo, err := doSomething()
if err != nil {
return nil, err
}
return foo, nil
}
I guess the logic I want is:
if ((case.Expected != nil && actual == nil) ||
(case.Expected == nil && actual != nil)) {
t.Fatalf(...)
}
Is there a better way of just asserting for existence rather than comparing concrete types?