简体   繁体   中英

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.

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

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

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.

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

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

Currently I have 98% coverage but I nothing is missed based on the overview: Jacoco整体报道

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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