Jacoco Coverage of Utility Classes

Daniel

October 18, 2019

Issue

There are cases where you would like a utility class that only contains static fields, such as a DateTimeConstants class.

Example DateTimeConstants.java

In this case we have made a class that can be instantiated through its default constructor, but never is. Jacoco counts this in its code coverage report as there is a possibility a new instance of DateTimeContstants could be created. If you are using code coverage as a metric to determine if a build can pass or fail, this can affect a build as it will count as one method missed.

Possible Solutions

There are a few solutions to this issue:

Firstly we could instantiate out the class in a test as we are just testing the default constructor for the class. A test such as the below should be sufficient.

Solution 1 - Initialise the class

From Jacoco version 0.8.0, we can also create a private constructor for the utility class. Since this class can no longer be instantiated outside itself, Jacoco no longer counts it towards its code coverage metric.

Solution 2 - Private constructor

Finally we could also consider moving the constants class to an interface. Variables in an interface are public final and static by default so these do not need to be specified. Although popular in the early Java days, this is very unpopular now as interfaces should deal with the services a class can provide, not its data.

Solution 3 - Interface implementation
Solution 3 - Interface implementation

Conclusion

If you are using Jacoco version 0.8.0 or higher, i believe that the best solution is to use a private constructor in your utility class. This means you do not need to create a test to cover this case explicitly.

Daniel

Daniel

I am a Software Engineer working as part of the nerd.vision team, mainly working on the backend systems and agents. When I'm not squashing bugs, I enjoy travelling, gaming and experiencing new foods and cultures.