Testing private methods (don't do it)

by Charles Miller on March 28, 2003

Peter Ghali asks about testing private methods:

So how do people test private methods....my opinion is that you should test private methods at all. Adequate test coverage should cover these methods through testing of the public and protected methods that use the private methods. However....

I don't test private methods. Being able to quickly create, move around, and change the functionality of private methods is vital to remaining agile while developing.

There is a significant cost involved in changing the behaviour of your public interface: you have to make sure each caller can cope with the change. Sometimes you even have to write new tests for each caller because you have introduced some new edge-case that wasn't there before. Private methods, on the other hand, can always be tested by running the tests for the enclosing class. If you've introduced a new edge-case, you only ever have to write new tests for that one class. It's all self-contained.

If you have to test your private methods, or if you have to change your tests every time you change your private methods, this becomes a barrier to refactoring. The amount of work you have to do to improve your code becomes the amount needed to change the private methods, _plus_ that required to change the tests. As such, you're less likely to make the improvement.

If you have a thorough suite of tests for a class's exposed (non-private) interface, those tests should, by their nature, verify that any private method within the class also works. If this isn't the case, or if you have a private method so complex that it needs to be tested out of the context of its public callers, I would consider that a code-smell.

Previously: Code Kata

Next: Thread.run()