Skip to content

assert.ErrorAs: confusing error message #1343

@craig65535

Description

@craig65535

Typically, the target passed to errors.As has a zero value. But if the errors.As call is wrapped by assert.ErrorAs, this can lead to a confusing error message if the assertion fails:

--- FAIL: TestCustomErr (0.00s)
    main_test.go:32: 
                Error Trace:    /.../main_test.go:32
                Error:          Should be in error chain:
                                expected: %!q(PANIC=Error method: runtime error: invalid memory address or nil pointer dereference)
                                in chain: "file does not exist"
                Test:           TestCustomErr
                Messages:       index 1
FAIL

For expected:, it's printing the target. But in my case the target can't be printed until it's assigned a value, and I think printing the target is not useful anyway - I think what it should be doing instead is printing the type of the target:

--- FAIL: TestCustomErr (0.00s)
    main_test.go:32: 
                Error Trace:    /.../main_test.go:32
                Error:          Should be in error chain:
                                expected: "*main.customErr"
                                in chain: "file does not exist"
                Test:           TestCustomErr
                Messages:       index 1
FAIL

Here's the code I used:

package main

import (
	"errors"
	"fmt"
	"io/fs"
	"testing"

	"github.com/stretchr/testify/assert"
)

type customErr struct {
	err error
}

func (ce customErr) Error() string {
	return ce.err.Error()
}

func getErrs() []error {
	return []error{
		customErr{
			err: errors.New(`something`),
		},
		fs.ErrNotExist,
	}
}

func TestCustomErr(t *testing.T) {
	for i, err := range getErrs() {
		var aCustomErr customErr
		assert.ErrorAs(t, err, &aCustomErr, fmt.Sprintf(`index %v`, i))
	}
}

I am happy to submit a PR to address this.

Metadata

Metadata

Assignees

No one assigned

    Labels

    pkg-assertChange related to package testify/asserttype-errorIssue related to comparing values implementing the error interface

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions