Should Private/Protected methods be under unit test

tddunit testing

In TDD development, the first thing you typically do is to create your interface and then begin writing your unit tests against that interface. As you progress through the TDD process you would end-up creating a class that implements the interface and then at some point your unit test would pass.

Now my question is about the private and protected methods that I might have to write in my class in support of the methods/properties exposed by the interface:

  • Should the private methods in the class have their own unit tests?

  • Should the protected methods in the class have their own unit tests?

My thoughts:

  • Especially because I am coding to interfaces, I shouldn't worry about protected/private methods as they are black boxes.

  • Because I am using interfaces, I am writing unit tests to validate that the contract defined is properly implemented by the different classes implementing the interface, so again I shouldnt worry about the private/protected methods and they should be exercised via unit tests that call the methods/properties defined by the interface.

  • If my code-coverage does not show that the protected/private methods are being hit, then I don't have the right unit-tests or I have code thats not being used and should be removed.

Best Answer

No, I don't think of testing private or protected methods. The private and protected methods of a class aren't part of the public interface, so they don't expose public behavior. Generally these methods are created by refactorings you apply after you've made your test turn green.

So these private methods are tested implicitly by the tests that assert the behavior of your public interface.

On a more philosophical note, remember that you're testing behavior, not methods. So if you think of the set of things that the class under test can do, as long as you can test and assert that the class behaves as expected, whether there are private (and protected) methods that are used internally by the class to implement that behavior is irrelevant. Those methods are implementation details of the public behavior.