Feeds:
Posts
Comments

Posts Tagged ‘junit’

I read an interesting post from an ex-colleagues blog recently around the subject of unit testing private methods when testing object oriented code. I quote the original post here and my initial response.

“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 completely and utterly 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 protected your implementation using a unit testing framework.”

My initial response to the article follows:

I would normally say that if you think that a private method requires it’s own unit test then this is a good pointer towards the need to refactor the class – usually pushing the functionality of the private method into it’s own collaborating class.

However that is easier said that done when it comes to working with legacy code. In that situation I would probably refactor the method from private to protected and create tests in the correct package hierarchy (java specific I realise).

I suppose the answer depends on how pragmatic you’re willing to be (and how much code is greenfield development).

Read Full Post »