Firstly it is arguable that you should not be trying to directly test a private method on an abstract class, as tests should focus on the public methods, it should be upto the class where it uses private methods. However, if you do want to do this there is a way. In my case I was trying to use Test Driven Development to modify an existing code base without unit tests. Rather than retro-fit them to the rest of the code I wanted to minimise the code I was testing by directly testing a private method (which happened to be on an abstract class).
The method I chose used two sub-methods, one for testing abstract classes and one for testing private methods, and they actually fitted together really easily.
- Use Rhino Mocks test the abstract class – Rhino Mocks allows for testing of abstract classes using the ‘partial mock‘ concept.
- Use visual studio private accessors to access the private methods – If you have a version of Visual Studio that supports MS Test you can simply right click on a private method and choose ‘Create Private Accessor’. The accessor that is created accepts an instance of the class as a constructor, so when you pass in the Partial Mock created previously you end up with a class exposing the private methods as public that can be directly called… awesum!