Monday, 5 August 2013

Java: Test Coverage for Private Constructors

It is good practice to add private constructors to utility classes that are not thought to be instantiated. This is usually the case for final classes that only have static methods or provide constants (in the latter case I would suggest to use an interface).

Following this practice usually gives a bad surprise when looking at your Cobertura code-coverage report (or similar). The tool reports that the constructor is not covered - of course, because you cannot call it! This lowers your overall percentage for line-coverage and is a drawback when you otherwise try to achieve 100% line-coverage and also enforce this using mvn verify or similar methods.

Quality-Check contains a module called Quality-Test in its newest snapshot release. It includes a small utility class CoverageForPrivateConstructor which allows us to write a little JUnit-Test to provide line-coverage for the private constructor.

public void giveMeCoverageForMyPrivateConstructor() throws Exception {

This result in a code-coverage report with full test coverage also for the private constructor. Nice, isn't it?

1 comment:

lingjie shi said...

I accidentally viewed your blog and I was so amazed with your work that it touched the deepness of my heart and it made me sentimental. Thanks for posting. Visit my site to buy replica rolex