是否可以从坑覆盖范围计算中排除方法?

发布于 2025-01-31 04:22:29 字数 327 浏览 2 评论 0原文

我的Java项目包含此类形式的类:

public final class NotInstantiableClass {

    private NotInstantiableClass () {
    }

    // some utility functions

}

该类的构造函数无法调用。它的唯一目的是防止实例化此类。因此,该构造函数不能用单位测试覆盖。

因此,在进行坑突变测试时,该方法被列为在线覆盖结果中发现的。

有没有办法从覆盖范围计算中排除此方法?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

时光匆匆的小流年 2025-02-07 04:22:29

最好在公用事业课程中引发构造函数的例外:

private ClockHolder() {
    throw new UnsupportedOperationException();
}

然后,您可以通过反射测试这样的类:

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
void privateConstructor() {
    assertThatThrownBy(() -> TestUtils.invokePrivateConstructor(ClockHolder.class))
            .isInstanceOf(UnsupportedOperationException.class);
}

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);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文