本文介绍了NUnit的CollectionAssert对于类似的自定义类列表返回false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的课程:
public class MyClass
{
public string Name { get; set; }
public string FaminlyName { get; set; }
public int Phone { get; set; }
}
然后我有两个类似的列表:
Then I have two similar list:
List<MyClass> list1 = new List<MyClass>()
{
new MyClass() {FaminlyName = "Smith", Name = "Arya", Phone = 0123},
new MyClass() {FaminlyName = "Jahani", Name = "Shad", Phone = 0123}
};
List<MyClass> list2 = new List<MyClass>()
{
new MyClass() {FaminlyName = "Smith", Name = "Arya", Phone = 0123},
new MyClass() {FaminlyName = "Jahani", Name = "Shad", Phone = 0123}
};
问题是NUnit CollectionAssert总是返回false.
The problem is that NUnit CollectionAssert return false always.
CollectionAssert.AreEqual(list1,list2);
我是否缺少有关CollectionAssert测试的一些信息
Am I missing something about CollectionAssert test
推荐答案
AreEqual
检查对象的相等性.由于您没有覆盖 Equals
方法,因此如果引用不相等,它将返回 false
.
The AreEqual
checks for equality of the objects. Since you did not override the Equals
method, it will return false
in case the references are not equal.
您可以通过覆盖 MyClass
的 Equals
方法来解决此问题:
You can solve this by overriding the Equals
method of your MyClass
:
public class MyClass {
public string Name { get; set; }
public string FaminlyName { get; set; }
public int Phone { get; set; }
public override bool Equals (object obj) {
MyClass mobj = obj as MyClass;
return mobj != null && Object.Equals(this.Name,mobj.Name) && Object.Equals(this.FaminlyName,mobj.FaminlyName) && Object.Equals(this.Phone,mobj.Phone);
}
}
您还更好地重写了 GetHashCode
方法:
You furthermore better override the GetHashCode
method as well:
public class MyClass {
public string Name { get; set; }
public string FaminlyName { get; set; }
public int Phone { get; set; }
public override bool Equals (object obj) {
MyClass mobj = obj as MyClass;
return mobj != null && Object.Equals(this.Name,mobj.Name) && Object.Equals(this.FaminlyName,mobj.FaminlyName) && Object.Equals(this.Phone,mobj.Phone);
}
public override int GetHashCode () {
int hc = 0x00;
hc ^= (this.Name != null) ? this.Name.GetHashCode() : 0;
hc ^= (this.FaminlyName != null) ? this.FaminlyName.GetHashCode() : 0;
hc ^= this.Phone.GetHashCode();
return hc;
}
}
这篇关于NUnit的CollectionAssert对于类似的自定义类列表返回false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!