Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assert to compare two lists of objects C#

I am currently trying to learn how to use unit testing, and I have created the actual list of 3 animal objects and the expected list of 3 animal objects. The question is how do I Assert to check the lists are equal? I have tried CollectionAssert.AreEqual and Assert.AreEqual but to no avail. Any help would be appreciated.

The test method:

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

    }
like image 632
JamesZeinzu Avatar asked Oct 24 '13 09:10

JamesZeinzu


People also ask

How to compare two lists in assert?

To compare two lists specifically, TestNG's Assert class has a method known as assertEquals(Object actual, Object expected) and there is an extended version of this method with customized message as assertEquals(Object actual, Object expected, String message). if the elements of the lists are in the same order.

How to check if 2 lists are the same c#?

To determine if two lists are equal, where frequency and relative order of the respective elements doesn't matter, use the Enumerable. All method. It returns true if every element of the source sequence satisfy the specified predicate; false, otherwise.


2 Answers

That is correct, as the lists might look the same, they are 2 different objects containing the same data.

In order to compare lists, you should use the CollectionAssert

CollectionAssert.AreEqual(expected, actual);

That should do the trick.

like image 54
pazcal Avatar answered Sep 16 '22 23:09

pazcal


Just incase someone comes across this in the future, the answer was I had to create an Override, IEqualityComparer as described below:

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

}

like image 42
JamesZeinzu Avatar answered Sep 16 '22 23:09

JamesZeinzu