mardi 4 avril 2017

Testing non-opaque error values

Is there a best practice for comparing non-opaque error values in Go?

Most code bases seem to treat errors as opaque (either the operation succeeded or it failed, with no visibility into internal details about what caused the error).

This makes it easy to write unit tests since all you need to do is assert the actual error against the expected error. The most I've seen people do in addition to that is compare error strings to make sure that it includes at minimum some key information. For example:

if err == nil || !strings.Contains(err.Error(), "not found in the Raft configuration") {
  t.Fatalf("err: %v", err)
}

But for cases where the additional error information is needed (like in form validation where you need to specify the invalid field name, the value, an error code and possibly some nested errors too), what do you do?

I can't simply do a reflect.DeepEqual() since the error will contain a unique stack trace which will make the comparison fail every time. Also, having nested errors makes the testing logic even more complex and you'll need all kinds of error-prone logic (loops, recursion) to compare the desired fields. Is there a standard way of testing errors of this nature?

Aucun commentaire:

Enregistrer un commentaire