I am testing a helper class with only static methods with JUnit4 and Cobertura. Testing methods was easy task and is done already.
However, cobertura shows that the class is not covered by tests completely, as it is not instantiated anywhere.
I don't want to create an instance of this class (it is a helper class), so first solution is to hide constructor (which is generally good approach for helper class).
Then cobertura complains that the empty private constructor is not covered by tests.
Is there any solution to achieve 100% code coverage for such situation?
Code coverage is required from top level management (in this case), so for me obtaining 100% for this particular class is quite helpful.
There are several solutions:
You can add a public constructor and call it from a test. While it doesn't make sense, it also doesn't hurt (much).
Create a dummy static instance (you can call the private constructor here). Ugly but you can give the field a name to communicate your intent (JUST_TO_SILENCE_COBERTURA
is a good name).
You can let your test extend the helper class. That will intrinsically call the default constructor but your helper class can't be final
anymore.
I suggest the last approach especially because the class can't be final
anymore. If a consumer of your code wants to add another helper method, they can now extend the existing class and receive one handle to get to all helper methods. This creates a coupling of the helper methods which communicates the intent (these belong together) - which is impossible if the helper class is final
If you want to prevent users to accidentally instantiate the helper class, make it abstract
instead of using a hidden constructor.