go-cmpでerrorを比較する
外部パッケージが非公開のエラー型や *errors.errorString を返す場合、単に文字列が一致するかで比較したい場合は次のように書ける:
code:cmp.go
type literalError struct {
msg string
}
func (e *literalError) Error() string { return e.msg }
func (e *literalError) Is(other error) bool {
if e == nil {
return other == nil
}
if other == nil {
return false
}
return e.msg == other.Error()
}
func diffErrorsConservatively(want, got error) string {
return cmp.Diff(want, got, cmpopts.EquateErrors())
}