I'm currently writing some unit tests for a package in which a function can return several types of errors. I've defined the struct as:
tests := []struct {
name string
data string
url string
status int
}
And would like to use errors.As()
to find test.err
within the error I test upon. An example struct that I used within my tests is for example:
{
name: "url not available",
err: &url.Error{},
data: srvData,
url: "a",
status: http.StatusOK,
},
I want to use errors.As
for different struct types that implement the error interface. Hence as you can see within the struct I have defined err as error. As can be seen I use &url.Error{}
which should be implementing the error interface.
t.Run(test.name, func(t *testing.T) {
data, err := i.getID(url)
if err != nil {
require.NotNil(t, test.err)
assert.True(t, errors.As(err, &test.err))
} else {
// ...
}
})
However, using errors.As
as above returns
second argument to
errors.As
should not be *error
Now to my understanding errors.As() accepts any
as second argument, so I'm confused as to why I can't use *error.
I have also tried changing the err
field within the test struct to interface{} instead; however doing so made all assertion pass, regardless of whether the target was present within the error.
I couldn't find a solution on how to use errors.As()
for different types that implement the error interface in a similar fashion as above, so for now I rely on using Contains()
instead. Was wondering if anyone could provide some insight.