Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create unit tests involving collections in c#?

I have a number of methods in C# which return various collections which I wish to test. I would like to use as few test APIs as possible - performance is not important. A typical example is:

HashSet<string> actualSet = MyCreateSet();
string[] expectedArray = new string[]{"a", "c", "b"};
MyAssertAreEqual(expectedArray, actualSet);

//...

void MyAssertAreEqual(string[] expected, HashSet<string> actual)
{
    HashSet<string> expectedSet = new HashSet<string>();
    foreach {string e in expected)
    {
        expectedSet.Add(e);
    }
    Assert.IsTrue(expectedSet.Equals(actualSet));
}

I am having to write a number of signatures according to whether the collections are arrays, Lists, ICollections, etc. Are there transformations which simplify this (e.g. for converting an array to a Set?).

I also need to do this for my own classes. I have implemented HashCode and Equals for them. They are (mainly) subclassed from (say) MySuperClass. Is it possible to implement the functionality:

void MyAssertAreEqual(IEnumerable<MySuperClass> expected, 
                      IEnumerable<MySuperClass> actual); 

such that I can call:

IEnumerable<MyClassA> expected = ...;
IEnumerable<MyClassA> actual = ...; 
MyAssertAreEqual(expected, actual); 

rather than writing this for every class

like image 929
peter.murray.rust Avatar asked Dec 18 '22 06:12

peter.murray.rust


1 Answers

Both NUnit and MSTest (probably the other ones as well) have a CollectionAssert class

  • CollectionAssert (NUnit 2.5)
  • CollectionAssert for MSTest
like image 51
jeroenh Avatar answered Jan 15 '23 00:01

jeroenh