C# generics and testing

Posted on Tuesday, July 14, 2009 by Nicki

The power of C# generics, you just gotta love it.


I'm writing NUnit unit tests for the business objects of the application. All the factory objects happen to have a LoadById method that takes an int as parameter, and return a typed list.

This is beautiful, as I can write a generic test method that for the factory type and list type, and then just write a one-liner test for every factory I want to test.

The generic method:

public void TestGeneric(int logicalRecord) where L : new()
{
L list = new L();
Type x = typeof(L);
MethodInfo LoadMethod = x.GetMethod("LoadById");
List records = (List)LoadMethod.Invoke(list, new object[] { logicalRecord });
Assert.IsTrue(records.Count > 0);
}



Invoking the generic method with the Factory type and the List type
            TestGeneric(logicalRecord);


You just gotta love generics. More info here

0 Responses to "C# generics and testing":