Assert.AreEqual失败,与同类型 [英] Assert.AreEqual fails with the same type

查看:381
本文介绍了Assert.AreEqual失败,与同类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我测试两个对象(和它们的集合),但即使它们具有相同类型的失败:

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

我已经做了,因为引用,他们可能是不同的,也许一些研究和。然而,它仍然是相同的类型,我不知道是什么Assert方法使用。 (该CollectionAssert.AreEquivalent也会失败)。

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

编辑

我也想,以检查是否每个字段的值是相同的,在这种情况下,我应该做一个Assert.AreEqual每个字段?

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

推荐答案

如果你想为你的DTO对象的比较值,则必须重写等于 GetHash code 方法。

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

例如给出的类:

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

如果你认为使用相同的名称DTOPersona类的两个对象(而不是地址)的等效对象(即同一人),你的code可能是这个样子:

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

这篇关于Assert.AreEqual失败,与同类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆