NUnit comparing two lists

SOfanatic picture SOfanatic · Nov 8, 2013 · Viewed 28.2k times · Source

OK so I'm fairly new to unit testing and everything is going well until now. I'm simplifying my problem here, but basically I have the following:

[Test]
public void ListTest()
{
    var expected = new List<MyClass>();
    expected.Add(new MyOtherClass());
    var actual = new List<MyClass>();
    actual.Add(new MyOtherClass());
    Assert.AreEqual(expected,actual);
    //CollectionAssert.AreEqual(expected,actual);
}

But the test is failing, shouldn't the test pass? what am I missing?

Answer

matth picture matth · Nov 8, 2013

If you're comparing two lists, you should use test using collection constraints.

Assert.That(actual, Is.EquivalentTo(expected));

Also, in your classes, you will need to override the Equals method, otherwise like gleng stated, the items in the list are still going to be compared based on reference.

Simple override example:

public class Example
{
    public int ID { get; set; }

    public override bool Equals(object obj)
    {
        return this.ID == (obj as Example).ID;
    }
}