diff --git a/errorassertion.go b/errorassertion.go index e7a9bf3..36e945b 100644 --- a/errorassertion.go +++ b/errorassertion.go @@ -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. @@ -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()) @@ -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()) diff --git a/errorassertion_test.go b/errorassertion_test.go index 3d02e7c..4421a6f 100644 --- a/errorassertion_test.go +++ b/errorassertion_test.go @@ -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 }