diff --git a/CHANGELOG.md b/CHANGELOG.md index 8656247..4dba78b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,11 @@ and this library adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased](https://github.com/fluentassert/verify/compare/v1.1.0...HEAD) +### Added + +- Add `FailureMessage.Err` method together with `AssertionError` type + to represent assertion results as `error` type. + ## [1.1.0](https://github.com/fluentassert/verify/releases/tag/v1.1.0) - 2024-02-06 This release adds length assertions. diff --git a/assertion_error.go b/assertion_error.go new file mode 100644 index 0000000..fe61b41 --- /dev/null +++ b/assertion_error.go @@ -0,0 +1,12 @@ +package verify + +// AssertionError is an error type used to represent failure messages from assertions. +// It is compatible with the error interface and can be used in instances where an error shall be returned instead of failing a test. +type AssertionError struct { + Message FailureMessage +} + +// Error returns the failure message as a string. It makes AssertionError compatible with the error interface. +func (err *AssertionError) Error() string { + return string(err.Message) +} diff --git a/failmsg.go b/failmsg.go index e0e04c8..a61c1a8 100644 --- a/failmsg.go +++ b/failmsg.go @@ -82,3 +82,12 @@ func (msg FailureMessage) Prefix(s string) FailureMessage { } return FailureMessage(s) + msg } + +// Err returns the failure message as an error type, or nil if the message is empty. +func (msg FailureMessage) Err() *AssertionError { + if msg == "" { + return nil + } + + return &AssertionError{Message: msg} +} diff --git a/failmsg_test.go b/failmsg_test.go index baf6da0..5b24672 100644 --- a/failmsg_test.go +++ b/failmsg_test.go @@ -137,6 +137,18 @@ func TestFailureMessage(t *testing.T) { assertEqual(t, got, "[fail] errored") }) }) + + t.Run("AsError", func(t *testing.T) { + t.Run("With Message", func(t *testing.T) { + got := verify.FailureMessage("failed").Err() + assertEqual(t, got.Error(), "failed") + }) + + t.Run("Empty", func(t *testing.T) { + got := verify.FailureMessage("").Err() + assertEqual(t, got, nil) + }) + }) } type errorMock struct {