简体   繁体   中英

Why does this else condition not meet code coverage?

I'm confused about why the following if/else condition doesn't meet code coverage. Specifically the else is getting flagged as not having coverage.

if (myBoolean) {
    myComponent.myElement = 'Hello world';
} else {
    myComponent.myElement = 'Hello everyone';
}

I can refactor this to set the value of myComponent.myElement prior to the if condition, and that seem to pass fine.

myComponent.myElement = 'Hello everyone';
if (myBoolean) {
    myComponent.myElement = 'Hello world';
}

Why wouldn't the else condition pass as well?

The coverage tool records which lines of code your tests cause to be executed.

If your flag is set by reading some input, then the flag is used to decide which branch to take, the test will follow either one path or the other. If your code under test checks for invalid inputs, code handling that won't be executed by a test using valid inputs. You will need a test for each possible case so that all the paths get covered.

By the way, the coverage tool is useful not just for the statistics it generates but for confirming the test does what you think it does. If a test fails you can look at the coverage and see how far it got and which branches were executed.

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