given a Golang function like this:
func GetKey(key string, data map[string]string) (string, error) {
value, present := data[key]
if !present {
return "", errors.New(fmt.Sprintf("requested key does not exist: %s", key))
}
return value, nil
}
how would i go about testing the presence of the error I return, using Test Tables? For example:
func TestGetKey(t *testing.T) {
cases := []struct {
Input map[string]string
Key string
Result string
Err error
}{
{
map[string]string{
"foo": "bar",
"baz": "bah",
},
"foo",
"bar",
nil,
},
{
map[string]string{
"foo": "bar",
"baz": "bah",
},
"nope",
"",
????,
},
}
// and something like
for _, v := range cases {
actual, err := GetKey(v.Key, v.Input)
if actual != v.Result {
t.Fatalf("Expected %s. Got %s", v.Result, actual)
}
}
}
Maybe I'm not seeing something, but this is usually how I do it:
actual, err := GetKey(v.Key)
if err != v.Err {
t.Errorf("Unexpected error: %s", err)
}
Or, if the returned error might not be a specific known error value, I might flatten to a string:
actual, err := GetKey(v.Key)
var errMsg string
if err != nil {
errMsg = err.Error()
}
if errMsg != v.errMsg {
t.Errorf("Unexpected error: %s", errMsg)
}
You could store the same error you are expecting to get and then assert that both return the same Error()
.
So in your map, for the error case:
{
map[string]string{
"foo": "bar",
"baz": "bah",
},
"nope",
"",
errors.New("requested key does not exist: nope"),
}
And in your test code:
for _, v := range cases {
actual, err := GetKey(v.Key, v.Input)
if actual != v.Result {
t.Fatalf("Expected %s. Got %s", v.Result, actual)
}
if (v.Err != nil) && (err == nil) {
t.Fatalf("Expecting error (%s), did not get it", v.Err.Error())
} else if (v.Err == nil) && (err != nil) {
t.Fatalf("Got unexpected error: (%s)", err.Error())
} else if (v.Err != nil) && (err != nil) && (v.Err.Error() != err.Error()) {
t.Fatalf("Expecting error (%s). Got (%s)", v.Err.Error(), err.Error())
}
}
Note that there are several cases for when you don't expected an error but actually got one, expected one and did not get it, and expected one and got a different one.