Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 403
GabeMeister Avatar asked Feb 04 '17 00:02

GabeMeister


People also ask

How do I run a go Unit Test?

At the command line in the greetings directory, run the go test command to execute the test. The go test command executes test functions (whose names begin with Test ) in test files (whose names end with _test.go). You can add the -v flag to get verbose output that lists all of the tests and their results.

Is error a type in go?

error is a built-in interface type in Go. An error variable represents any value that can describe itself as a string . The interface consists of a single function, Error() , that returns a string error message.


1 Answers

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

like image 184
Omar Avatar answered Oct 26 '22 20:10

Omar