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

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)

paz*_*cal 9

这是正确的,因为列表可能看起来相同,它们是包含相同数据的 2 个不同对象。

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

CollectionAssert.AreEqual(expected, actual);
Run Code Online (Sandbox Code Playgroud)

这应该够了吧。

  • 嗯,CollectionAssert.AreEqual 不起作用,它说:CollectionAssert.AreEqual 失败。(索引 0 处的元素不匹配。) (3认同)
  • 一旦您将自定义 IComparer 与 CollectionAssert.AreEqual 一起使用,它应该可以工作。应该是第三个参数。请参阅 http://msdn.microsoft.com/de-de/library/vstudio/ms243703.aspx (2认同)

Jam*_*nzu 6

以防万一将来有人遇到这个问题,答案是我必须创建一个覆盖,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)

}