Search code examples
c#listunit-testingcollectionsassert

C# compare lists List<T>


using Microsoft.VisualStudio.TestTools.UnitTesting;

I want universal test method, which gets Dictionary and function, and then check equality for each dictionary entry between Value and function(Key):

public void TestMethod<TKey, TValue>(Dictionary<TKey, TValue> dict, Func<TKey, TValue> func)
{
    foreach (var test in dict)
    {
         Assert.AreEqual(test.Value, func(test.Key));
    }
}

But if Values (and return value of function) is

List<int>

it doesnt work, of course. So, I found than I need

CollectionAssert.AreEqual

for such cases. But now I have to say, that my value is System.Collections.ICollection. How to do this?


Solution

  • You need to cast the values to ICollection so the compiler won't complain.

    public void TestMethod<TKey, TValue>(Dictionary<TKey, TValue> dict, Func<TKey, TValue> func)
    {
        foreach (var test in dict)
        {
             if (test.Value is ICollection)
             {
                  CollectionAssert.AreEqual((ICollection)test.Value, (ICollection)func(test.Key));
             }
             else
             {
                  Assert.AreEqual(test.Value, func(test.Key));
             }
        }
    }