Since Microsoft decided to remove the creation of private accessors for unit tests in Visual Studio 2012, one have to get familiar with the usage of Microsoft.VisualStudio.TestTools.UnitTesting.PrivateObject
.
This class offers an easy way to call methods, independent from their visibility, via reflection. The method is PrivateObject.Invoke
. This method saves you from getting the MethodInfo
before being able to invoke an object’s ‘hidden’ method.
Sometimes methods do have out
parameters. I was asking myself how to define these parameters when calling a method via reflection. When the method returns, I wanted to be able to read the value set by the method called.
I expected somthing tricky. But the solution is very simple: Just add an element to the array of parameters, and after the call access the appropriate element of the array.
The code goes like this:
ClassWithPrivateMethods instance = new ClassWithPrivateMethods(); PrivateObject privateObject = new PrivateObject(instance); object[] args = new object[] { "some value", null /* placeholder for out param */ }; privateObject.Invoke("PrivateMethodHavingOutParameter", args); var outParameterValue = args[1];