switch 语句的 Jacoco 覆盖率

Jacoco coverage for switch statement

我正在努力为我正在使用的库实现 100% 的代码覆盖率,我似乎对 switch 语句和覆盖率有一些问题,我根本不明白。

我目前使用的是 Jacoco 0.7.2,因为每个更新的版本似乎都与 Robolectrics 不兼容。

我测试了一个简单的switch语句:

public enum Type {
    NONE, LEGACY, AKS
}

private static Class<?> getCipherClass(Type type) {
    switch (type) {
        case LEGACY:
            return CipherWrapperLegacy.class;
        case AKS:
            return CipherWrapperAks.class;
        default:
            return null;
    }
}

我写的测试包含以下检查(我必须使用反射,因为该方法是私有的):

final CipherWrapper instance = CipherWrapper.createInstance(mockContext, CipherWrapper.Type.LEGACY, ALIAS);
assertNotNull(instance);

Method getCipherMethod = TestUtils.makeMethodAccessible(CipherWrapper.class, "getCipherClass", CipherWrapper.Type.class);
assertNull(getCipherMethod.invoke(instance, CipherWrapper.Type.NONE));
assertEquals(CipherWrapperAks.class, getCipherMethod.invoke(instance, CipherWrapper.Type.AKS));
assertEquals(CipherWrapperLegacy.class, getCipherMethod.invoke(instance, CipherWrapper.Type.LEGACY));

结果不是我所期望的:

图像有点混乱,因为黄线表示缺少某些内容。绿色图标告诉我 3 个分支中的 3 个被覆盖。

我还测试了用 case NONE 扩展 switch case 并失败了,但它没有改变任何东西。

我唯一能做的就是用 if/else 替换开关,然后我得到 100% 的覆盖率。

目前我有 98% 的覆盖率,但根据概述,我没有遗漏任何东西:

如果 invoke 方法不喜欢你放入匿名变量:

getCipherMethod.invoke(instance, (CipherWrapper.Type) null);

然后用命名变量试试:

CipherWrapper.Type nullType = null;
getCipherMethod.invoke(instance, nullType);

此外,您应该检查调用异常是否只是包装由调用方法引起的异常而不是调用本身的错误。