Goのエラーのメッセージを取得する

テスト時にエラーメッセージのバリデーション

こういうケースはよくあると思いますが。

userDBに対してFind処理を行った際にエラーのチェックを行いたいケース。

       _, err := user.FindUser(user)

        if err.Error() != "user ID is invalid" {
            t.Errorf("Error message is invalid: %v", err)
        }

このようにError()でメッセージが取れるようです。

エラーメッセージのconst化

エラーメッセージは変わりやすいので、テストが壊れやすいです。 なので、それをconst値として公開しておくケースが好まれるようです

github.com

const (
    ErrNotFound   = DictionaryErr("could not find the word you were looking for")
    ErrWordExists = DictionaryErr("cannot add word because it already exists")
)

type DictionaryErr string

func (e DictionaryErr) Error() string {
    return string(e)
}

ErrNotFoundのようにconstにして外に公開しておいて、それをテストで参照する方法。