1

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?

Florian
  • 4,821
  • 2
  • 19
  • 44
  • Does this help? https://stackoverflow.com/questions/37742396/pitest-excludedmethods-maven – JustAnotherDeveloper May 20 '22 at 10:15
  • Just tried it out. No, this doesn't help. These parameters allow me to exclude classes and methods from the _mutation_ coverage. However, this is about the _line_ coverage. – Florian May 24 '22 at 13:55

1 Answers1

2

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);
}
Ivan Vakhrushev
  • 340
  • 2
  • 9
  • 1
    I'd prefer not to create such utility classes that is just possible to test with reflection. But this is solution if needed. – Alexey Antipin Sep 17 '22 at 18:08