4

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

peter.murray.rust
  • 37,407
  • 44
  • 153
  • 217

3 Answers3

8

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

jeroenh
  • 26,362
  • 10
  • 73
  • 104
4

If you are using .NET 3.5 you can use the Enumerable.SequenceEqual method.

Assert.IsTrue(seqA.SequenceEqual(seqB));

You should use OrderBy on both sequences prior to calling SequenceEqual if you only care about the elements being equal and not the order.

Mike Two
  • 44,935
  • 9
  • 80
  • 96
  • 1
    Shouldn't it be Enumerable.SequenceEqual instead of IEnumerable? – Michael Jul 30 '09 at 07:20
  • 1
    @Michael: It's an extension method, so you can just use `seqA.SequenceEqual(seqB)`. It's *very important* to note that you need to use `OrderBy(...)` to have meaningful comparisons (you care about the existence of elements, but not about the order). – Sam Harwell Jul 30 '09 at 07:25
  • Edited answer to reflect good suggestions from @Michael and @280Z28 – Mike Two Jul 30 '09 at 08:17
0

Have you tried using the CollectionAssert that comes with NUnit.

It asserts against the two collections and compares the items within the collection

AutomatedTester
  • 22,188
  • 7
  • 49
  • 62