A small thing that caught me out today, while writing a unit test for C# I wanted to check that a list was returned in the expected order and used Assert.AreEqual to compare them, this kept failing despite the two lists being exactly the same.
It turns out that there is a separate CollectionsAssert class that is to be used for lists or any form of C# collection and that is due to the List<T> class not overriding the Equals method, the AreEqual function will just check the references instead.
Here is an example of a working unit test comparing two lists.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
using System; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace TestFunctions { [TestClass] public class SortedTupleDictionaryTest { [TestMethod] public void TestSortedDictionaryTupleOrder() { SortedDictionary<Tuple<int, int, int>, string> dict = new SortedDictionary<Tuple<int, int, int>, string>(); dict.Add(Tuple.Create(1, 1, 1), "apple"); dict.Add(Tuple.Create(1, 2, 1), "chair"); dict.Add(Tuple.Create(1, 1, 2), "bear"); dict.Add(Tuple.Create(2, 2, 1), "deer"); List<Tuple<int, int, int>> expected = new List<Tuple<int, int, int>>(); expected.Add(Tuple.Create(1, 1, 1)); expected.Add(Tuple.Create(1, 1, 2)); expected.Add(Tuple.Create(1, 2, 1)); expected.Add(Tuple.Create(2, 2, 1)); CollectionAssert.AreEqual(expected, dict.Keys); } } } |
Questions? Comments?