Skip to content

Commit

Permalink
feat: ✨ make nil ErrorAssertion a valid option (#40)
Browse files Browse the repository at this point in the history
  • Loading branch information
zoido committed May 25, 2024
1 parent b168d11 commit 93decab
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
13 changes: 12 additions & 1 deletion errorassertion.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
package errassert

// ErrorAssertion represents single single instance of the error assertion.
// ErrorAssertion represents a single instance of the error assertion.
// If the error is not as expected, call returns an error.
//
// Zero value (nil) is valid and Assert nor Require will never fail. It can be looked at as
// "I don't care about the error" assertion.
type ErrorAssertion func(error) error

// TestingT defines the subset of testing.TB methods used by errassert.
Expand All @@ -14,6 +17,10 @@ type TestingT interface {

// Assert checks if the error is as expected and calls t.Fail if not.
func (assertion ErrorAssertion) Assert(t TestingT, err error) {
if assertion == nil {
return
}

t.Helper()
if tErr := assertion(err); tErr != nil {
t.Log(tErr.Error())
Expand All @@ -23,6 +30,10 @@ func (assertion ErrorAssertion) Assert(t TestingT, err error) {

// Require checks if the error is as expected and calls t.FailNow if not.
func (assertion ErrorAssertion) Require(t TestingT, err error) {
if assertion == nil {
return
}

t.Helper()
if tErr := assertion(err); tErr != nil {
t.Log(tErr.Error())
Expand Down
15 changes: 15 additions & 0 deletions errorassertion_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,21 @@ func TestErrorAssertion_Require_Fail(t *testing.T) {
mockT.AssertLogfCalledWith(t, failMsg)
}

func TestErrorAssertion_NilFunctional(t *testing.T) {
// Given
mockT := NewMockT()
var assertion errassert.ErrorAssertion

// When
assertion.Assert(mockT, anError)
assertion.Require(mockT, anError)

// Then
mockT.AssertNotFailed(t)
mockT.AssertNotFailedNow(t)
mockT.AssertLogfNotCalled(t)
}

func passAssertion(error) error {
return nil
}
Expand Down

0 comments on commit 93decab

Please sign in to comment.