Jam*_*nzu 5 c# tdd unit-testing assert
我目前正在尝试学习如何使用单元测试,并且我已经创建了 3 个动物对象的实际列表和 3 个动物对象的预期列表。问题是我如何断言检查列表是否相等?我试过 CollectionAssert.AreEqual 和 Assert.AreEqual 但无济于事。任何帮助,将不胜感激。
测试方法:
[TestMethod]
public void createAnimalsTest2()
{
animalHandler animalHandler = new animalHandler();
// arrange
List<Animal> expected = new List<Animal>();
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<Animal> actual = animalHandler.createAnimals("","","",0,0,0);
//assert
//this is the line that does not evaluate as true
Assert.Equals(expected ,actual);
}
Run Code Online (Sandbox Code Playgroud)
这是正确的,因为列表可能看起来相同,它们是包含相同数据的 2 个不同对象。
为了比较列表,您应该使用CollectionAssert
CollectionAssert.AreEqual(expected, actual);
Run Code Online (Sandbox Code Playgroud)
这应该够了吧。
以防万一将来有人遇到这个问题,答案是我必须创建一个覆盖,IEqualityComparer,如下所述:
public class MyPersonEqualityComparer : IEqualityComparer<MyPerson>
{
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;
}
Run Code Online (Sandbox Code Playgroud)
}
| 归档时间: |
|
| 查看次数: |
21815 次 |
| 最近记录: |