Unit Testing – Best Practices for Code Coverage of Empty Interface Methods

clean codetest-coverageunit testing

Given a class that implements an interface, but does not need all of the methods implemented, what is the best practice for unit testing this class with respect to code coverage? – or is it considered a sign for a code smell?

To make the problem more concrete, consider a Java class (the question is not limited to Java though) that implements ComponentListener but derives from some X (so as to rule out the choice to use ComponentAdapter). The class is however only interested in the componentResized() method and leaves the other callback method bodies empty.

When checking the code coverage, we get a report that indicates correctly that the remaining methods are untested. For obvious reasons, I hesitate to add a test that simply calls a no-op method for the sake of coverage.

While I am not bound to reach a certain coverage, I still think that in and of itself, this phenomenon may indicate a code smell with respect to the single-responsibility principle. On the other hand, it's not far-fetched either that a component representation is responsible for updating its state on a resize.

Is there some sort of consensus or best practice on how to handle such methods, or is the question illegitimate as in it is a result of a supposedly bad design?

Best Answer

I'm not sure what the best practice would be but to me, your problem isn't a problem of empty interface methods - it's a problem that your interfaces are wrong.

If you implement an interface, implement the entire interface - if the interface is too broad or has functionality that you're not interested in then split the interface and have the main interface implement sub-interfaces and have your component only implement the bit that's appropriate.