Search code examples
unit-testinggoerror-handling

How to unit test Go errors


When you are unit testing functions that have an error return type, I was wondering how to properly unit test for this error. Are you supposed to just check if the error is nil or not nil? Or are you supposed to verify the error string matches an expected string as well?


Solution

  • 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. (2025 EDIT: Use errors.Is: https://pkg.go.dev/errors#example-Is) 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