My Java project contains a class of this form:
public final class NotInstantiableClass {
private NotInstantiableClass () {
}
// some utility functions
}
The constructor of this class cannot be invoked. Its sole purpose is to prevent instantiation of this class. Consequently, this constructor cannot be covered with unit tests.
Also consequently, when running PIT mutation tests, this method is listed as uncovered in the line coverage results.
Is there a way to exclude this method from the coverage calculation?
It's better to throw an exception from constructor in utility classes:
private ClockHolder() {
throw new UnsupportedOperationException();
}
Then you can test such classes via reflection:
public final class TestUtils {
@SuppressWarnings("checkstyle:IllegalThrows")
public static <T> void invokePrivateConstructor(@Nonnull final Class<T> type)
throws Throwable {
final Constructor<T> constructor = type.getDeclaredConstructor();
constructor.setAccessible(true);
try {
constructor.newInstance();
} catch (InvocationTargetException ex) {
throw ex.getTargetException();
}
}
Test will be look like
@Test
void privateConstructor() {
assertThatThrownBy(() -> TestUtils.invokePrivateConstructor(ClockHolder.class))
.isInstanceOf(UnsupportedOperationException.class);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With