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