golang test : use assert to compare addresses leads to runtime crash

Viewed 29

I'm trying to compare 2 addresses, I can write code like p == q, but inside ```assert, it leads to run time problem, as below:

import (
    "testing"

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

func TestAddress(t *testing.T) {
    assert := assert. New(t)
    p := new(int)
    q := new(int)
    assert.NotEqual(p, q) // error

    var a struct{}
    var b struct{}
    assert. Equal(a, b)

    i1 := new([0]int)
    i2 := new([0]int)
    assert.NotEqual(i1, i2) // error
}

The error message is:

Error Trace:    d:\mycode\basic_test.go:11

            Error:          Should not be: (*int)(0xc0000178b8)

            Test:           TestAddress

Error Trace:    d:\mycode\basic_test.go:19

            Error:          Should not be: &[0]int{}

            Test:           TestAddress

What does this error message indicate? How to fix it?

1 Answers

As per assert.NotEqual documentation

NotEqual asserts that the specified values are NOT equal.

a.NotEqual(obj1, obj2)

Pointer variable equality is determined based on the equality of the referenced values (as opposed to the memory addresses).

Given that p and q points to the same value, the assertion fails, resulting in those error messages.

Related