How to unit test Go errors
In most cases you can just check if the error is not nil.
I'd recommend not checking error strings unless absolutely necessary. I generally consider error strings to be only for human consumption.
If you need more detail about the error, one better alternative is to have custom error types. Then you can do a switch over the err.(type) and see if it's a type you expect. If you need even more detail, you can make the custom error types contain values which you can then check in a test.
Go's error is just an interface for a type that has an Error() string
method, so implementing them yourself is straightforward.
https://blog.golang.org/error-handling-and-go
The testify package will come in handy.
From the docs: "EqualErrorf asserts that a function returned an error (i.e. not nil
) and that it is equal to the provided error.":
assert.EqualErrorf(t, err, expectedErrorMsg, "Error should be: %v, got: %v", expectedErrorMsg, err)
To assert that the error message contains a substring:
assert.Containsf(t, err.Error(), tt.wantErrMsg, "expected error containing %q, got %s", tt.wantErrMsg, err)
t is of type
*testing.T
anderr
is of typeerror