简体   繁体   中英

Assert.AreEqual fails with the same type

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

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))

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());

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 (ie 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);
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM