You can use CollectionAssert
with generic collections. The trick is to understand that the CollectionAssert
methods operate on ICollection
, and although few generic collection interfaces implement ICollection
, List<T>
does.
Thus, you can get around this limitation by using the ToList
extension method:
IEnumerable<Foo> expected = //...
IEnumerable<Foo> actual = //...
CollectionAssert.AreEqual(expected.ToList(), actual.ToList());
That said, I still consider CollectionAssert
broken in a lot of other ways, so I tend to use Assert.IsTrue(bool)
with the LINQ extension methods, like this:
Assert.IsTrue(expected.SequenceEqual(actual));
FWIW, I’m currently using these extension methods to perform other comparisons:
public static class EnumerableExtension
{
public static bool IsEquivalentTo(this IEnumerable first, IEnumerable second)
{
var secondList = second.Cast<object>().ToList();
foreach (var item in first)
{
var index = secondList.FindIndex(item.Equals);
if (index < 0)
{
return false;
}
secondList.RemoveAt(index);
}
return secondList.Count == 0;
}
public static bool IsSubsetOf(this IEnumerable first, IEnumerable second)
{
var secondList = second.Cast<object>().ToList();
foreach (var item in first)
{
var index = secondList.FindIndex(item.Equals);
if (index < 0)
{
return false;
}
secondList.RemoveAt(index);
}
return true;
}
}