I have a class that's annotated with @UtilityClass like this
@UtilityClass
public class myUtilClass {
...
}
JaCoCo doesn't give me full coverage for this class because of the auto-generated code created by the annotation @UtilityClass .
Ideally, I do not want to change any config files to ignore auto-gen code. How can this code be tested?
The only "coverable" code that is generated by @UtilityClass is in the constructor:
private MyUtilClass() {
throw new UnsupportedOperationException("This is a utility class and cannot be instantiated");
}
As this is a private constructor that never should be called, you cannot test it regularly.
If you really want to call it, you can do it with some ugly reflective code:
Constructor<MyUtilClass> constructor;
constructor = MyUtilClass.class.getDeclaredConstructor();
constructor.setAccessible(true);
constructor.newInstance();
But you should not do this just for the sake of coverage. Having a high coverage is generally a good idea, but not if you have to sacrifice good testing standards.
I suggest you advice JaCoCo to ignore Lombok's code by adding this line to your lombok.config file:
lombok.addLombokGeneratedAnnotation = true
You don't have to configure this for your whole project. If you put this file only into the package of MyUtilClass, JaCoCo will only ignore generated code in this package.
Just write this unit test to ensure your class cannot be instantiated because of @UtilityClass annotation. Then, coverage will be OK.
@Test
void test_cannot_instantiate() {
assertThrows(InvocationTargetException.class, () -> {
var constructor = YOUR_CLASS_NAME.class.getDeclaredConstructor();
assertTrue(Modifier.isPrivate(constructor.getModifiers()));
constructor.setAccessible(true);
constructor.newInstance();
});
}