3

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
}
4
  • 1
    I'm guessing you're using the github.com/stretchr/testify/assert package, but you may want to be explicit about that in your question, to lift any ambiguity.
    – jub0bs
    Apr 17, 2022 at 11:46
  • 2
    Your sample doesn't compile in the first place. Adding one character makes it ok syntactically, but it's still wrong in that it is missing a return.
    – torek
    Apr 17, 2022 at 11:46
  • Sorry, I have addressed both of your comments.
    – Slim
    Apr 17, 2022 at 11:56
  • 2
    use assert.Nil to test for nil values
    – blackgreen
    Apr 17, 2022 at 20:23

1 Answer 1

8

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.