Extending the NUnit Framework
After a long while working with NUnit, and the NUnit team not wanting my additions, I feel that this is my best outlet for a simple update that covers a missing core assumption in the testing framework. Currently the framework supports Assert.AreEqual() on the core data types, but leaves out support for collections and lists, really anything that is of IEnumerable. So i have written a new class full of tests, and extended the NUnit framework to support Assert.AreEqual(IEnumerable, IEnumerable).
Download Assert.cs and EnumerableEqualsFuxture.cs.
Changes to Assert.cs, add the following 3 functions:
static private void AreEqual(IEnumerator expected, IEnumerator actual) {
Assert.AreEqual(expected, actual, string.Empty) ;
}
static private void AreEqual(IEnumerator expected, IEnumerator actual, string message) {
int actualCount = 0, expectedCount = 0;
expected.Reset();
actual.Reset();
while (expected.MoveNext()) { expectedCount++; }
while (actual.MoveNext()) { actualCount++ ; }
Assert.AreEqual(expectedCount, actualCount, "Enumerable objects, counts are not equal.");
expected.Reset();
actual.Reset();
actualCount = 0;
while (expected.MoveNext() && actual.MoveNext()) {
actualCount++;
Assert.AreEqual(expected.Current, actual.Current, string.Format( "Enumerable objects, {0}{1} item:{2}", actualCount, NumberEnding(actualCount), message));
}
}
static private string NumberEnding(int number) {
switch (number % 10 ) {
case 1 : return "st" ;
case 2 : return "nd" ;
case 3 : return "rd" ;
default : return "th" ;
}
}
Also add the commented section to ObjectEquals
static private bool ObjectsEqual(Object expected, Object actual) {
//add starts here for IEnumerable support
if ((expected is IEnumerable) && !(expected is string) &&
(actual is IEnumerable) && !(actual is string)) {
if (expected.GetType().Equals(actual.GetType())) {
Assert.AreEqual(((IEnumerable)expected).GetEnumerator(),
((IEnumerable)actual).GetEnumerator());
return true;
}
}
//add ends here for IEnumerable support
if (IsNumericType(expected) && IsNumericType(actual)) {
string = expected.ToString();
string = actual.ToString();
return sExpected.Equals(sActual);
}
return expected.Equals(actual);
}
Now assert away on your collections and lists.