I am trying to assert a function that returns a nil, but i'm trying to assert nil but the following assertion doesn't make sense.
I am using the github.com/stretchr/testify/assert
framework to assert
passes: assert.Equal(t, meta == nil, true)
fails: assert.Equal(t, meta, nil)
I am not sure why this makes any sense. could someone help please.
Method being tested:
type Metadata struct {
UserId string
}
func GetAndValidateMetadata(metadata map[string]string) (*Metadata, error) {
userId _ := metadata["userId"]
if userId == "" {
return nil, errors.New("userId is undefined")
}
meta := Metadata{
UserId: userId,
}
return &meta, nil
}
testcase:
func TestValidation(t *testing.T) {
metadata := map[string]string{
"fakeUserId": "testUserId",
}
meta, err := GetAndValidateMetadata(metadata)
assert.Equal(t, meta == nil, true) <--- passes
assert.Equal(t, meta, nil) <--- fails
}
CodePudding user response:
Interface values in Go store a type and a value of that type.
The equal method takes interface{} arguments, so in the second assertion you are comparing an interface value containing type information (*Metadata) and a nil value to an interface without type information and a nil value.
You can force the second interface to also contain a type like so:
assert.Equal(t, meta, (*Metadata)(nil))
See also "Why is my nil error value not equal to nil?" in the FAQ.