I have a error type like below defined
type RetryableError struct {
msg string
}
func (a *RetryableError) Error() string {
return a.msg
}
In a unit test, what is the Go way of asserting if the error returned is of RetryableError
type?
I have a error type like below defined
type RetryableError struct {
msg string
}
func (a *RetryableError) Error() string {
return a.msg
}
In a unit test, what is the Go way of asserting if the error returned is of RetryableError
type?
Use type assertion:
err := someFunc()
if retryable, ok := err.(*RetryableError); ok {
// use retryable
}
Your RetryableError
is not an error, but *RetryableError
is. To correct:
func (a RetryableError) Error() string {
return a.msg
}
Snippet from https://medium.com/@sebdah/go-best-practices-testing-3448165a0e18:
func TestDivision(t *testing.T) {
tests := []struct{
x float64
y float64
result float64
err error
}{
{ x: 1.0, y: 2.0, result: 0.5, err: nil },
{ x: -1.0, y: 2.0, result: -0.5, err: nil},
{ x: 1.0, y: 0.0, result: 0.0, err: ErrZeroDivision},
}
for _, test := range tests {
result, err := divide(test.x, test.y)
assert.IsType(t, test.err, err)
assert.Equal(t, test.result, result)
}
}