How can I create unit tests with collections in C #?

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

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 need to write several signatures depending on whether the collections are arrays, lists, ICollections, etc. Are there any transformations that simplify this (for example, to convert an array to Set?).

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

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

so that I can call:

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

instead of writing this for each class

+4
source share
3 answers

Both NUnit and MSTest (possibly others) also have a CollectionAssert class

+7
source

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

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

You should use OrderBy for both sequences before calling SequenceEqual if you only care about equal elements, not order.

+4
source

You tried using CollectionAssert , which comes with NUnit.

He argues against two collections and compares elements within the collection.

0
source

All Articles