Tuesday, 14 October 2008

Call private methods of an object from a test assembly. (NUnit)

I have to test a class of Foo from my test assembly Foo.Test.
Unfortunately, many methods I should test are not public.

This class uses reflection to call private methods on any type or object for testing.

using System;
using System.Reflection;

namespace TestUtilities
{
public class TestHelper
{
public static object InvokeStaticMethod(System.Type type, string methodName, object[] parameters)
{
BindingFlags bindFlags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
return InvokeMethod(type, methodName, null, parameters, bindFlags);
}
public static object InvokeInstanceMethod(System.Type type, object instance, string methodName, object[] parameters)
{
BindingFlags bindFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
return InvokeMethod(type, methodName, instance, parameters, bindFlags);
}
private static object InvokeMethod(System.Type type, string methodName, object instance, object[] parameters, BindingFlags bindFlags)
{
MethodInfo methInfo;
methInfo = type.GetMethod(methodName, bindFlags);
if (methInfo == null)
{
throw new ArgumentException(String.Format("There is no method with name {0} on type {1}", methodName, type.Name));
}

object result = methInfo.Invoke(instance, parameters);
return result;
}

}
}

No comments: