简体   繁体   English

为什么代码覆盖率有时会计算方法名称或右括号?

[英]Why code coverage sometimes counts method name or closing bracket?

Why these lines like method definitions (line with modifiers, method name, arguments etc) or closing brackets counts sometimes into line coverage? 为什么这些行,例如方法定义(带有修饰符,方法名称,参数等的行)或右括号有时会计入行覆盖范围?

例1

In this particular example it is a constructor method, but it's not always like that: 在此特定示例中,它是一个构造函数方法,但并非总是这样:

例题

Can you explain that? 你能解释一下吗?

This depends on what coverage tool you are using, but I've seen some that match your results. 这取决于您所使用的覆盖率工具,但我已经看到一些与您的结果相符的工具。

The reason, so far as I can tell, is throw/early-return vs hitting the end of the function. 据我所知,原因是抛出/提前返回vs到达函数的结尾。

Note that the only method you have with the closing brace highlighted does not return (anything), instead running off the end of the function and so touching the closing brace (and the stack-popping that probably happens there). 请注意,唯一带有突出显示的右括号的方法不会返回(任何东西),而是从函数的结尾运行,然后触摸右括号(以及可能在此处发生的堆栈弹出)。 Same for the constructor, which does not explicitly return anywhere within the function. 与构造函数相同,该构造函数不会在函数内的任何位置显式返回。

In the other examples, the last highlighted line is where execution leaves the function. 在其他示例中,最后突出显示的行是执行离开函数的位置。

You can test this pretty easily by setting up a method that returns early, and testing only that case while collecting coverage. 您可以通过设置一种可以早日返回的方法并在收集覆盖率的同时仅测试该案例来轻松测试。 Test the other (return off the end) case with coverage, and compare the two. 用覆盖率测试另一种情况(结束),然后将两者进行比较。 Hopefully, the second shows the closing brace highlighted. 希望第二个显示突出显示的右括号。

For example: 例如:

public class EarlyReturn {
    public static void whatHappens(final Boolean path) {
        System.out.println("Entering method...");

        if (path == null) {
           throw new IllegalArgumentException("Must have a path.");
        } else if (path) {
            System.out.println("Exiting early...");
            return;
        }

        System.out.println("Exiting normally...");
    }
}

with: 有:

@RunWith(JUnit4.class)
public class TestEarlyReturn {
    @Test
    public void testEarly() {
        EarlyReturn.whatHappens(true);
    }

    @Test
    public void testNormal() {
        EarlyReturn.whatHappens(false);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testThrow() {
        EarlyReturn.whatHappens(null);
    } 
}

You haven't mentioned line/branch coverage metrics, but in your example, all cases should have 100% coverage (I would hope). 您没有提到行/分支覆盖率指标,但是在您的示例中,所有情况下的覆盖率都应为100%(我希望如此)。 This, of course, still depends on the tool and how it samples. 当然,这仍然取决于工具及其采样方式。 My example should not have 100% line coverage, unless you run both tests together. 我的示例不应具有100%的线路覆盖率,除非您同时运行两个测试。

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

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