Jacoco对switch语句的报道 [英] Jacoco coverage for switch statement

查看:178
本文介绍了Jacoco对switch语句的报道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为正在使用的库获取100%的代码覆盖率,而且switch语句和覆盖率似乎有些问题,我根本无法理解。

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.

我当前正在使用Jacoco 0.7.2,因为每个新版本似乎都与Robolectrics一起使用。

I am currently using Jacoco 0.7.2 because every newer version seems to break with Robolectrics.

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

I test a simple switch statement:

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

结果不是我所期望的:

该图像有点令人困惑,因为黄线表示缺少某些内容。绿色图标告诉我覆盖了3个分支中的3个。

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.

我还测试了扩展开关盒的情况,其中 case NONE 并且掉了下来,但是它什么都没有改变。

I also tested to extend the switch case with case NONE and a fall through but it didn't change anything.

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

The only thing I can do is to replace the switch with if/else and then I get 100% coverage.

当前,我有98%的覆盖率,但根据概览,我什么都不会错过:

Currently I have 98% coverage but I nothing is missed based on the overview:

推荐答案

如果invoke方法不喜欢您输入匿名变量:

If the invoke method doesn't like you putting in an anonymous variable:

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.

这篇关于Jacoco对switch语句的报道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆