我的Java项目包含此表单的一个类:
public final class NotInstantiableClass {
private NotInstantiableClass () {
}
// some utility functions
}不能调用该类的构造函数。它的唯一目的是防止此类的实例化。因此,这个构造函数不能包含在单元测试中。
因此,在运行坑突变测试时,这种方法被列在行覆盖结果中。
是否有办法将此方法排除在覆盖率计算之外?
发布于 2022-09-17 17:27:33
最好在实用程序类中从构造函数中抛出异常:
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);
}https://stackoverflow.com/questions/72317134
复制相似问题