Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to exclude methods from PIT coverage calculation?

Tags:

java

pitest

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?

like image 923
Florian Avatar asked Oct 26 '25 08:10

Florian


1 Answers

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);
}
like image 140
Ivan Vakhrushev Avatar answered Oct 28 '25 22:10

Ivan Vakhrushev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!