Should private methods be unit tested?

Once in a while this question pops up. Should private methods in classes be unit tested? My short answer to this question is no. If a private method is complex enough to require unit tests. Then it should be moved to its own class and be public.

If you are still trying to grasp the concept of unit testing, please read my post on this here.

Testing private methods

Private methods are always tested when you test your public methods - how else would they be invoked? Therefore I see them as a fraction of a public implementation. Private methods are often created during refactoring - a simple way of grouping a block of code and giving it a name. Without the public method the private method makes no sense. Therefore I believe that private methods should be seen as part of the public method.

Testing private methods tests the inner workings of a class. Meaning if you later come back to refactor the class, you may invalidate a lot of tests. All your tests for the public methods might still be green but your tests for the private methods are now invalid or failing - even if you have not changed the input/output of the public method.

Test-driven development

An argument I often hear is, well what about TDD? - when you write something you have to test it! That is true. But how often do you start by writing a private method? You would start by writing the public method - and then at some point extract the private one. Then it is already tested due to it being part of the public one. As your development is driven by tests, which is driven by contracts for your class (which may come from a specification - but often not) - then you will start by testing and writing your public methods.

These were my opinions on testing private methods, agree or disagree? Let me know in the comments!