When writing unit tests, I frequently find myself wanting to test private methods. I used to think there were only three approaches to solving this problem.
- Test the private method indirectly through some other, public method that invokes it.
- Pros: Keeps your class interface clean and doesn't compromise your OO design
- Cons: You may not be able to test all of the cases you'd like through the public method, and your test results may be affected by the code in the public method.
- Pros: Allows you test the method directly
- Cons: Compromises the encapsulation of your initial design, requires writing more test classes.
- Pros: Doesn't require more test code, you may actually end up with more well-factored design
- Cons: You probably don't want to make this code public, isn't that why it was private in the first place?
- Use reflection to invoke the private method directly
- Pros: Totally rocks.
- Cons: Invoking the private method looks a little funky
public class TestReflector
public static T InvokeNonPublicMethod<T>( string methodName, object obj,
params object parameters )
MethodInfo methodInfo =
obj.GetType().GetMethod( methodName, BindingFlags.NonPublic |
if ( methodInfo == null )
throw new ApplicationException( "Private method not found for: '" +
methodName + "'." );
return (T)methodInfo.Invoke( obj, parameters );
With that in place, it's very simple to use:
MyClass myClass = new MyClass();
string string1 = "abcdef";
string string2 = "123456";
string result = TestReflector.InvokeNonPublicMethod<string>(
"MyPrivateMethod", myClass, string1, string2 );
This code will support any non-public method with any number of parameters and any return type, except void. If you do need void support, its a simple adaptation of this code. Hope this helps!