Skip to content
This repository was archived by the owner on Feb 17, 2025. It is now read-only.

Commit 83844e9

Browse files
authored
Add FailureMessage.Err method and AssertionError type (#141)
1 parent 7b197d1 commit 83844e9

File tree

4 files changed

+38
-0
lines changed

4 files changed

+38
-0
lines changed

CHANGELOG.md

+5
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,11 @@ and this library adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
77

88
## [Unreleased](https://github.com/fluentassert/verify/compare/v1.1.0...HEAD)
99

10+
### Added
11+
12+
- Add `FailureMessage.Err` method together with `AssertionError` type
13+
to represent assertion results as `error` type.
14+
1015
## [1.1.0](https://github.com/fluentassert/verify/releases/tag/v1.1.0) - 2024-02-06
1116

1217
This release adds length assertions.

assertion_error.go

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package verify
2+
3+
// AssertionError is an error type used to represent failure messages from assertions.
4+
// It is compatible with the error interface and can be used in instances where an error shall be returned instead of failing a test.
5+
type AssertionError struct {
6+
Message FailureMessage
7+
}
8+
9+
// Error returns the failure message as a string. It makes AssertionError compatible with the error interface.
10+
func (err *AssertionError) Error() string {
11+
return string(err.Message)
12+
}

failmsg.go

+9
Original file line numberDiff line numberDiff line change
@@ -82,3 +82,12 @@ func (msg FailureMessage) Prefix(s string) FailureMessage {
8282
}
8383
return FailureMessage(s) + msg
8484
}
85+
86+
// Err returns the failure message as an error type, or nil if the message is empty.
87+
func (msg FailureMessage) Err() *AssertionError {
88+
if msg == "" {
89+
return nil
90+
}
91+
92+
return &AssertionError{Message: msg}
93+
}

failmsg_test.go

+12
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,18 @@ func TestFailureMessage(t *testing.T) {
137137
assertEqual(t, got, "[fail] errored")
138138
})
139139
})
140+
141+
t.Run("AsError", func(t *testing.T) {
142+
t.Run("With Message", func(t *testing.T) {
143+
got := verify.FailureMessage("failed").Err()
144+
assertEqual(t, got.Error(), "failed")
145+
})
146+
147+
t.Run("Empty", func(t *testing.T) {
148+
got := verify.FailureMessage("").Err()
149+
assertEqual(t, got, nil)
150+
})
151+
})
140152
}
141153

142154
type errorMock struct {

0 commit comments

Comments
 (0)