From c2116b41944a93870cbf8d8b207523ec2e98efc8 Mon Sep 17 00:00:00 2001 From: ccoVeille <3875889+ccoVeille@users.noreply.github.com> Date: Thu, 8 May 2025 15:44:35 +0200 Subject: [PATCH] Improve ErrorAs failure message when error is nil Before: Should be in error chain: expected: *assert.customError in chain: After: An error is expected but got nil. expected: *assert.customError The message `An error is expected but got nil.` is the one already reported by `assert.Error` --- assert/assertions.go | 8 +++++++- assert/assertions_test.go | 5 ++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/assert/assertions.go b/assert/assertions.go index 0ed1eed09..3353b33a2 100644 --- a/assert/assertions.go +++ b/assert/assertions.go @@ -2202,11 +2202,17 @@ func ErrorAs(t TestingT, err error, target interface{}, msgAndArgs ...interface{ return true } + expectedText := reflect.ValueOf(target).Elem().Type().String() + if err == nil { + return Fail(t, fmt.Sprintf("An error is expected but got nil.\n"+ + "expected: %s", expectedText), msgAndArgs...) + } + chain := buildErrorChainString(err, true) return Fail(t, fmt.Sprintf("Should be in error chain:\n"+ "expected: %s\n"+ - "in chain: %s", reflect.ValueOf(target).Elem().Type(), chain, + "in chain: %s", expectedText, chain, ), msgAndArgs...) } diff --git a/assert/assertions_test.go b/assert/assertions_test.go index 16dc2587d..77a151856 100644 --- a/assert/assertions_test.go +++ b/assert/assertions_test.go @@ -3402,9 +3402,8 @@ func TestErrorAs(t *testing.T) { err: nil, result: false, resultErrMsg: "" + - "Should be in error chain:\n" + - "expected: *assert.customError\n" + - "in chain: \n", + "An error is expected but got nil.\n" + + `expected: *assert.customError` + "\n", }, { err: fmt.Errorf("abc: %w", errors.New("def")),