断言比较两个对象列表C#

我目前正在尝试学习如何使用unit testing,并且我已经创建了3个动物对象的实际列表以及3个动物对象的预期列表。 问题是我如何断言检查列表是否相等? 我尝试过CollectionAssert.AreEqual和Assert.AreEqual,但无济于事。 任何帮助,将不胜感激。

测试方法:

[TestMethod] public void createAnimalsTest2() { animalHandler animalHandler = new animalHandler(); // arrange List expected = new List(); Animal dog = new Dog("",0); Animal cat = new Cat("",0); Animal mouse = new Mouse("",0); expected.Add(dog); expected.Add(cat); expected.Add(mouse); //actual List actual = animalHandler.createAnimals("","","",0,0,0); //assert //this is the line that does not evaluate as true Assert.Equals(expected ,actual); } 

只是想让某人在未来遇到这个,答案是我必须创建一个Override,IEqualityComparer,如下所述:

 public class MyPersonEqualityComparer : IEqualityComparer { public bool Equals(MyPerson x, MyPerson y) { if (object.ReferenceEquals(x, y)) return true; if (object.ReferenceEquals(x, null)||object.ReferenceEquals(y, null)) return false; return x.Name == y.Name && x.Age == y.Age; } public int GetHashCode(MyPerson obj) { if (object.ReferenceEquals(obj, null)) return 0; int hashCodeName = obj.Name == null ? 0 : obj.Name.GetHashCode(); int hasCodeAge = obj.Age.GetHashCode(); return hashCodeName ^ hasCodeAge; } 

}

这是正确的,因为列表是包含类似数据的2个不同对象。

为了获得比较列表,您应该使用CollectionAssert

 CollectionAssert.AreEqual(expected ,actual); 

这应该够了吧。