Assert.AreEqual fails with the same type

点点圈 提交于 2019-12-13 06:32:09

问题


I'm testing two objects (and a collection of them) but it fails even though they have the same type:

I have done some research and its maybe because of the references, which they could be different. However, its still the same type and I don't know what Assert method to use. (The CollectionAssert.AreEquivalent also fails).

Edited

I'm also trying to check if the values of each field are the same, in that case, should I do an Assert.AreEqual for each field?

-- thanks, all of the answers were helpful


回答1:


If you want to compare values for your dto objects then you have to override Equals and GetHashCode methods.

For example given the class:

public class DTOPersona
{
    public string Name { get; set; }
    public string Address { get; set; }
}

If you consider that two objects of DTOPersona class with the same Name (but not Address) are the equivalent objects (i.e. the same person), your code could look something like this:

public class DTOPersona
{
    public string Name { get; set; }
    public string Address { get; set; }

    protected bool Equals(DTOPersona other)
    {
        return string.Equals(Name, other.Name);
    }

    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj))
        {
            return false;
        }
        if (ReferenceEquals(this, obj))
        {
            return true;
        }
        if (obj.GetType() != this.GetType())
        {
            return false;
        }
        return Equals((DTOPersona) obj);
    }

    public override int GetHashCode()
    {
        return (Name != null ? Name.GetHashCode() : 0);
    }
}



回答2:


You should be comparing the type of the object. As you correctly identified, the content of the object may be different and as such they cannot be considered equal.

Try something like

Assert.AreEqual(typeof(ObjectA), typeof(ObjectB))




回答3:


Assert.AreEqual checks that two objects are the same, not that they are simply of the same type. To do that you'd do:

Assert.AreEqual(A.GetType(), B.GetType());



回答4:


Without adding some comparison logic you won't be able to know if your class instance is the same from data point of view with another.

In order to check if all fields have the same value you could override Object.GetHashCode and Object.Equals method.

Doing a field by field comparison would work too.



来源:https://stackoverflow.com/questions/13825663/assert-areequal-fails-with-the-same-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!