Unit Testing a Private Method of an Abstract C# Class
I have a certain degree of sympathy with the view that if you need to do this then there’s something architecturally wrong. But the question came up recently and those familiar with the code were adamant that it was as well factored as it could be. Unfortunately it wasn’t very clear how to test such a method.
So we have a class and a method.
The stumbling point is that clearly an instance of Derived does not have access the private methods of Base, and that you can’t get an instance of Base as that’s abstract. The auto-generated templates provided by Visual Studio leave a few too many // TODOs to be particularly useful.
The crudest method is plain old reflection:
Note that we are use .BaseType to walk up the hierarchy.
The Visual Studio Unit Test libraries have a PrivateObject accessor that wraps this much more nicely
Or if you use the accessor assemblies you can do
If you find you are doing this a lot then in the brave new world of C# 4 you could use dynamics to make it a little slicker still
This relies on a DynamicAccessor class of the following form: