Aaron Thomas Aaron Thomas -4 years ago 108
C# Question

C# unit testing with collections of collections

To piggyback on this SO question...

How does this test fail?

[TestMethod]
public void DummyTest() {
var expected = new List<List<string>>() {
new List<string>(){ "123456", "25.6", "15", "a" },
new List<string>(){ "123457", "3107450.82", "1", "bcdef" },
new List<string>(){ "123458", "0.01", "900000", "-fgehk" }
};

var actual = new List<List<string>>() {
new List<string>(){ "123456", "25.6", "15", "a" },
new List<string>(){ "123457", "3107450.82", "1", "bcdef" },
new List<string>(){ "123458", "0.01", "900000", "-fgehk" }
};

CollectionAssert.AreEqual(expected, actual);
}


By the way,
Assert.IsTrue(expected.SequenceEqual(actual));
also fails.

Is there a better way to test collections of collections?

Using .NET 4.6.1.

Answer Source

That comparison method is going to look at the first item from each collection, check using the default comparer for that type if they're equal, and if not, consider the outer collections unequal. It'll then go on to check the other elements in the same manner.

The default equality comparer for List<string> is going to compare the references of the two objects, not compare the underlying values of the two lists, because List doesn't change that default behavior from object.

You could write your own IComparer that knows how to checks if two collections are actually equal, and provide that comparer to CollectionAssert, if you want the items in the inner collections to be compared using the values of the items in the collection.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download