Showdown: Testing Private Methods vs Public Methods

   Submit to Reddit      

The concept of testing private methods has been debated by many people, and up until now I have been happy to sit on the fence.

However, recently I have been looking at simplifying and optimising automated testing code. As part of that process, I created a small sample application with one public service operation method that calls a number of private methods.

In order to answer the question about whether there are worthwhile advantages to testing private methods, I decided to do a shoot-out of automated testing code. Here was the line up:

  • All the test code required to thoroughly test the sample application by testing both private and public methods; and
  • All the test code required to thoroughly test the sample application by testing just the public methods.

The result was conclusive: in order to thoroughly test the sample application, less test cases were required and significantly less automated testing code was required when just explicitly testing the public methods (and implicitly testing the logic in private methods).

Here is a summary of my findings.

  • Less test cases were required because test cases for the logic contained within the private methods overlapped with test cases that were still required in order to thoroughly test the public methods;
  • The private methods were still thoroughly tested implicitly through the test cases for the public methods; and
  • The resulting test code was less brittle so developers can more freely refactor the application code without easily breaking the test code.

Don't believe me? Perform a similar exercise for yourself!

comments powered by Disqus