简体   繁体   English

Jacoco承保开关声明

[英]Jacoco coverage for switch statement

I am working to get 100% code coverage for a library I am working on and I seem to have some issues with a switch statement and the coverage which I simply don't understand. 我正在努力为我正在处理的库获得100%的代码覆盖率,而且我似乎对switch语句和我根本不理解的覆盖范围有一些问题。

I am currently using Jacoco 0.7.2 because every newer version seems to break with Robolectrics. 我目前正在使用Jacoco 0.7.2,因为每个新版本似乎都与Robolectrics打破。

I test a simple switch statement: 我测试一个简单的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;
    }
}

The test I wrote contains the following checks (I have to use reflection as the method is private): 我写的测试包含以下检查(我必须使用反射,因为方法是私有的):

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));

The result is not what I have expected: 结果不是我所期望的:

Jacoco代码覆盖结果

The image is a bit confusing as the yellow line suggests that there is something missing. 图像有点混乱,因为黄线表示缺少某些东西。 The green icon tells me that 3 of 3 branches are covered. 绿色图标告诉我3个分支中有3个被覆盖。

I also tested to extend the switch case with case NONE and a fall through but it didn't change anything. 我还测试了延长开关盒的情况,没有case NONE和掉落,但它没有改变任何东西。

The only thing I can do is to replace the switch with if/else and then I get 100% coverage. 我唯一能做的就是用if / else替换开关,然后我得到100%的覆盖率。

Currently I have 98% coverage but I nothing is missed based on the overview: 目前我有98%的覆盖率,但根据概述我没有遗漏: Jacoco整体报道

If the invoke method doesn't like you putting in an anonymous variable: 如果invoke方法不喜欢你输入一个匿名变量:

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

Then try it with a named variable: 然后使用命名变量尝试:

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

Also, you should check if the invocation exception is just wrapping an exception caused by invoking the method rather than an error with invocation itself. 此外,您应该检查调用异常是否只是包装由调用方法而不是调用本身的错误引起的异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM