Testing .NET Private Methods

If you’ve developed a .NET application, chances are you’ve used private methods in your design. Their inclusion brings about several advantages, but unit testing them isn’t immediately obvious. In fact, whether to unit test private methods at all is frequently debated, with opponents citing that they shouldn’t be considered because only a public interface is used in a real-world scenario.

I feel that private methods should be tested, because a core idea of unit testing is to test small units of functional code, which by definition, includes private methods.

Without question, private methods are trickier to unit test than public methods; at first glance, it isn’t obvious at all. Unit testing code is client code after all, and by definition, private methods aren’t visible. However, there are ways, and I present three of them here.

  1. Roll your own private method call using reflection
  2. Use the .NET InternalsVisibleTo attribute
  3. Use the test team API’s PrivateObject class