views:

250

answers:

3

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

+2  A: 

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
Shouldn't it be Enumerable.SequenceEqual instead of IEnumerable?
Michael
@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).
280Z28
Edited answer to reflect good suggestions from @Michael and @280Z28
Mike Two
A: 

Have you tried using the CollectionAssert that comes with NUnit.

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

AutomatedTester
+4  A: 

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

jeroenh
Thank you (I am using MSTest, I think). This looks like what I need. We are planning to move to NUnit RSN
peter.murray.rust