Monday, August 11, 2008

Listing all Test Methods in an Assembly Using C#


In order to write your own test runner you have to find out which methods of your assembly are marked with the attribute TestMethod.

This can be done easily using reflection as the following code example shows.


Assembly a = Assembly.LoadFrom("whatever.dll");
foreach (Type type in a.GetTypes())
{
if (type.IsDefined(typeof (TestClassAttribute), true))
{
MethodInfo[] methods = type.GetMethods();
foreach (MethodInfo method in methods)
{
if (method.IsDefined(typeof (TestMethodAttribute), true))
{
Console.Writeln(method.Name);
}
}
}
}



First we walk through all types of the assembly and search for the attribute TestClassAttribute.
Then we list all methods of the type and search for the attribute TestMethodAttribute.

In this example the result is simply written to the console.


Post a Comment