Unit Testing Private Methods?

There was a section of a lecture I attended by Robert C. Martin devoted to unit testing and the topic of writing unit tests for private methods was mentioned. So the question was “Should you write unit tests for private methods” and the answer was NO.

A class has an interface of public methods. Those public methods use private methods. You write test cases for the public methods to ensure all functionality the class provides is covered by tests. If you need to write unit tests specifically for the private methods, then your test cases for the public methods are probably not covering all cases, and if they do, then the tests for the private methods are just duplicates of the public method test cases. One of the main problems with unit tests on private methods is that they make it difficult to refactor the inner workings of a class.

A developer should have the freedom to refactor the code within a class without needing to re-write existing unit tests. We should be working at removing obstacles to refactoring and creating meaningful interfaces to our code that are both straight forward for development and testing. If you absolutely feel a private method in a class is complicated enough that it warrants being unit tested on it’s own, then perhaps that is functionality that should be broken out into it’s own class.

The public methods of a class are an interface. One job of unit tests is to explain the correct usage of a class to the next developer who uses it. Trying to unit test the private methods of a class will just make it more difficult for other developers to understand.