Saturday, November 23

Testing private methods via reflection

You are not supposed to test the private methods of a class, but it is occasionally useful. Microsoft used to have a private accessor type but has since deprecated it. This is the way I came up with: Put a pulic wrapper around the methods, and use reflection to call them. Not original, but it works ok.

The reflection class has one main method: RunMethod. I added (ok, started with) a ListMethod as a helper.

////// Executes the private method of the instance////// Method to execute as a string/// Parameters for the method/// The result of the method executionpublicobject RunMethod(string methodName, Object[] parameters)
{return AccessorReflection.RunMethod(objectInstance.GetType(), methodName, this.objectInstance, parameters);
}
}
}

So now write an accessor class with the public wrappers. My example is dumb but it gets the point across.