I think a lot of people when getting into unit testing naturally assume (and are told) that typically, a unit is a single method or function within your code, and each unit should have a unit test.

To an extent this is true – until you are presented with what you do with protected or private methods within classes.

There are two camps of thought on this issue.

One (that I disagree with) says that these methods ARE units in their own right, and should be tested as such (using introspection, or language hacks etc). In PHP this can be accomplished by abusing the __call method in your class (to allow a test suite to call protected or private methods on your class).

The second, is that a ‘unit’ is actually a single call to the public interface of your class. The protected and private methods that are called within the class are implementation details and should be allowed to be refactored entirely. Providing the behaviour and the public interface of the class does not change, refactoring does not involve ANY modification to the class itself.

Because the implementation details of a class do not constitute a unit in it’s own right, testing these methods in isolation are therefore incomplete and actually invalid (as they never have the context in which they are used, and even though your code may show 100% lines of code coverage, the branch coverage will always be far from complete).

So – if you’re tempted to create a test for a protected/private method within a class, then you’re moving away from unit tests and into protecting your implementation using a unit testing framework.