Testing errors in Go
Assert on the sentinel or the type, never on the message text.
var ErrBadStars = errors.New("stars out of range")
func Validate(stars int) error {
if stars < 0 || stars > 3 {
return fmt.Errorf("validate %d: %w", stars, ErrBadStars)
}
return nil
}
func TestValidate(t *testing.T) {
cases := []struct {
stars int
wantErr error
}{
{2, nil},
{9, ErrBadStars},
}
for _, c := range cases {
err := Validate(c.stars)
if !errors.Is(err, c.wantErr) {
t.Errorf("Validate(%d) = %v, want %v", c.stars, err, c.wantErr)
}
}
}
How it works
errors.Isis the right comparison for a wrapped error.- A wantErr field in the table covers both paths.
- Comparing
err.Error()breaks the moment you add context.
Keywords and builtins used here
errorforfuncifintrangereturnstructvar
The run, in numbers
- Lines
- 25
- Characters to type
- 452
- Tokens
- 124
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 74 seconds.
Step 4 of 4 in Writing tests, step 4 of 13 in Testing.