Using reflection to unit-test private methods

Situation

There is a class called “MyClass” which has a private method called “MyPrivateMethod” (which expects a single string parameter) that you want to unit-test.

Problem

You can’t access private methods from the test class by just calling them.

Solution

Use reflection to invoke the method. 

typeof(MyClass).GetMethod("MyPrivateMethod", BindingFlags.NonPublic | BindingFlags.Instance)
  .Invoke(null, new object[] { "MyStringParameter" });

Hint: Static methods require the BindingFlag “Static”.

Hint: If the invoked method throws an exception it will be wrapped inside a TargetInvocationException.

Alternative 1: change the scope of the private method to internal.
Advantages: Fast at runtime
Disadvantages: Mucks up the internal scope of the class.

Alternative 2: use Visual Studios private accessors.
Advantages: None
Disadvantages: Deprecated

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.