Different code coverage types and the importance of a good report
Tags: codereview, programming, devops, webdev
Published: 2022-08-25 13:43:19

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">You probably already know that code coverage tells us what percentage of our code is covered by tests. But did you know there are different coverage types and that the expressiveness of the coverage results depends on which type you choose?</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">In this article, we’ll take a deeper look at what code coverage is, which types of coverage exist, and the importance of having a good coverage report.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":1} -->
<h1 id="h-what-is-code-coverage"><strong>What is code coverage?</strong></h1>
<!-- /wp:heading -->

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">Your code is never going to be perfect. Even if you’re an experienced developer, it’s only natural that you’ll make mistakes at some point or forget particular scenarios. That’s why testing your code is such a critical part of the development lifecycle.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">In a nutshell, code coverage is a metric that specifies how much of your codebase is covered by tests. It is an essential metric because your tests might have good results, but if they only cover 20% of your codebase, it’s hard to be confident about the overall quality of the product.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":1} -->
<h1 id="h-the-different-types-of-code-coverage"><strong>The different types of code coverage</strong></h1>
<!-- /wp:heading -->

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">We’ll briefly explain line, branch, condition, and MC/DC coverage by looking at a simple example. Let’s assume you only go to the beach if it’s sunny and the weather forecast is good - meaning the temperature is between a specific range of degrees (those values are entirely up to you!).</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>boolean isBeachTime(boolean isSunny, boolean isGoodTemperature) {<br>     boolean isBeachWeather = false;<br>     if (isSunny &amp;&amp; isGoodTemperature) {<br>          isBeachWeather = true;<br>     }<br>     return isBeachWeather;<br>}</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">Yes, we could’ve simplified the code above to only return <code>(isSunny &amp;&amp; isGoodTemperature)</code>! However, we chose this version to illustrate the different coverage types.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">There are several ways to determine how well tests cover your code. Various metrics offer a different perspective on your code quality, and it’s helpful to know the basics of each of them. So now that we have our running example let’s dive in!</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2 id="h-line-coverage"><strong>Line coverage</strong></h2>
<!-- /wp:heading -->

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">Line coverage is probably the oldest and most common way of calculating code coverage. It tracks which lines of code your tests executed and gives you a percentage based on the total number of code lines.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">For our example, a single test case is enough to get full line coverage:</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>isBeachTime(true, true) == true;</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">But what happens if we have the following slightly modified code?</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>void showBeach(boolean isSunny, boolean isGoodTemperature) {
     Beach ourFavouriteBeach;
     if (isSunny &amp;&amp; isGoodTemperature) {
          ourFavouriteBeach = new Beach();
     }
     return ourFavouriteBeach.show();
}</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">We get full coverage with <code>showBeach(true, true)</code>, but if we call <code>showBeach(false, false)</code>, we’ll miss a NullPointerException, even though we have full line coverage. As such, line coverage can give us false confidence about the code’s quality.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2 id="h-branch-coverage-or-decision-coverage"><strong>Branch coverage (or decision coverage)</strong></h2>
<!-- /wp:heading -->

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">The problem with line coverage in the <code>showBeach</code> example is that it doesn’t force us to write tests so that every possible branch is visited. For that, there’s branch coverage, also known as decision coverage.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">A branch can occur due to <code>if</code> and <code>switch-case</code> statements, <code>while</code> loops, <code>catch</code> blocks, and other boolean expressions. Branch coverage sees the conditional logic branches in the code and ensures that tests cover all of them.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">To get full branch coverage for our example, we must consider every outcome of the boolean expression <code>(isSunny &amp;&amp; isGoodTemperature)</code>:</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>isBeachTime(true, true) == true;<br>isBeachTime(false, false) == false;</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">Thus, full branch coverage allows us to detect the NullPointerException in our modified example. However, there are more complicated code constructs where even branch coverage is insufficient.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2 id="h-condition-coverage"><strong>Condition coverage</strong></h2>
<!-- /wp:heading -->

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">Condition coverage analyzes code statements that include conditions, such as if-statements. It checks if there are tests for the conditions to be at least once <code>true</code> and once <code>false</code>.&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">Our example contains a single condition: <code>if (isSunny &amp;&amp; isGoodTemperature)</code></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The tests need to ensure that both <code>isSunny</code> and <code>isGoodTemperature</code> were at least once true and once false. We can achieve full condition coverage with the same tests for branch coverage:</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>isBeachTime(true, true) == true;<br>isBeachTime(false, false) == false;</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">However, condition coverage does not imply branch coverage. We reach full condition coverage with the following two tests, but not full branch coverage:</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>isBeachTime(true, false) == false;<br>isBeachTime(false, true) == false;</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">Condition coverage doesn't imply branch coverage as well.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2 id="h-modified-condition-decision-coverage-or-mc-dc"><strong>Modified condition / decision coverage (or MC/DC)</strong></h2>
<!-- /wp:heading -->

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">Modified condition / decision coverage, also known as MC/DC, can be seen as a combination of branch and condition coverage. As such, it’s stronger than both of them. MC/DC is used in safety-critical systems and is required in international standards like ISO 26262 and DO 178C.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">To achieve full MC/DC coverage, we have to make sure that:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>every boolean expression in a control statement takes all possible outcomes at least once (branch coverage);</li><li>every condition within a boolean expression takes all possible outcomes at least once (condition coverage); and</li><li>each condition has been shown to independently affect the outcome of the boolean expression (by varying just that condition while holding all other possible conditions).</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">MC/DC coverage has semantic requirements for tests. In our example, the tests have to reflect that the absence of either sun or good temperature can keep us from going to the beach. Look again at the two tests in branch coverage:</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>isBeachTime(true, true) == true;<br>isBeachTime(false, false) == false;</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">These tests satisfy the first two MC/DC criteria requirements: the boolean expression <code>(isSunny &amp;&amp; isGoodTemperature)</code> takes every possible outcome, and every predicate within that expression is at least once true and once false. However, the tests don’t satisfy the third requirement since they don’t capture that either <code>isSunny = false</code> or <code>isGoodTemperature = false</code> would be enough to make the boolean expression false.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">So let’s look at the second set of tests in condition coverage:</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>isBeachTime(true, false) == false;<br>isBeachTime(false, true) == false;</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">These tests satisfy the second and third requirements of the MC/DC criteria. However, in both tests, the boolean expression <code>(isSunny &amp;&amp; isGoodTemperature)</code> does not hold, so the first requirement is not satisfied.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>We need a combination to achieve full MC/DC coverage:</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>isBeachTime(true, true) == true;<br>isBeachTime(true, false) == false;<br>isBeachTime(false, true) == false;</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>These tests cover each requirement of the MC/DC coverage.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2 id="h-other-types-of-code-coverage"><strong>Other types of code coverage</strong></h2>
<!-- /wp:heading -->

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">There are others types of code coverage to keep in mind when thinking about your testing. We won’t dive into them in detail, but it’s still good to know they exist. Some examples include:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li><strong>Statement coverage:</strong> measures the number of code statements executed when the code runs. It helps uncover unused statements and branches, missing statements, and dead code.</li><li><strong>Function coverage:</strong> measures the number of declared functions covered by tests. It’s important in software that relies on a large number of functions.</li><li><strong>Path coverage:</strong> measures the number of linearly independent paths (given by <a href="https://blog.codacy.com/an-in-depth-explanation-of-code-complexity/" target="_blank" rel="noreferrer noopener">McCabe’s cyclomatic complexity</a>) covered by tests to identify broken, redundant, or inefficient paths.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":1} -->
<h1 id="h-the-importance-of-a-good-coverage-report"><strong>The importance of a good coverage report</strong></h1>
<!-- /wp:heading -->

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">If your test suite is automated (as it should!), you can run all your tests and have a tool like <a href="https://www.codacy.com/?utm_source=blog&amp;utm_medium=website&amp;utm_campaign=coverage-types" target="_blank" rel="noreferrer noopener">Codacy</a> to check the executed pieces of code. The ultimate power of code coverage is in the report.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">First of all, you'll get an overall coverage percentage. So, for example, the Codacy repository dashboard might tell you that your tests cover 48% of your code, which means you should add more tests.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":6405,"sizeSlug":"large","linkDestination":"none","tdCaptionAlign":"https://blog.codacy.com/wp-content/uploads/2022/08/Codacy-dashboard-Coverage.png"} -->
<figure class="wp-block-image aligncenter size-large td-caption-align-https://blog.codacy.com/wp-content/uploads/2022/08/Codacy-dashboard-Coverage.png"><img src="https://blog.codacy.com/wp-content/uploads/2022/08/Codacy-dashboard-Coverage-1024x925.png" alt="Codacy dashboard - Coverage" class="wp-image-6405"/><figcaption class="wp-element-caption">Codacy dashboard, with coverage</figcaption></figure>
<!-- /wp:image -->

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">The overall percentage isn't the only exciting information. Codacy also shows you a detailed view of code coverage per file. That way, you can focus first on areas with the lowest code coverage.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":6406,"sizeSlug":"large","linkDestination":"none","tdCaptionAlign":"https://blog.codacy.com/wp-content/uploads/2022/08/Codacy-files-Coverage.png"} -->
<figure class="wp-block-image aligncenter size-large td-caption-align-https://blog.codacy.com/wp-content/uploads/2022/08/Codacy-files-Coverage.png"><img src="https://blog.codacy.com/wp-content/uploads/2022/08/Codacy-files-Coverage-1024x681.png" alt="Codacy files - Coverage" class="wp-image-6406"/><figcaption class="wp-element-caption">Codacy files view, with coverage</figcaption></figure>
<!-- /wp:image -->

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">You can <a href="https://blog.codacy.com/diff-coverage/" target="_blank" rel="noreferrer noopener">define thresholds</a> where pull requests are not accepted if code coverage is below a specific percentage. This encourages your team to add tests to their code. Finally, when your code coverage increases, you should also increase the threshold. <a href="https://blog.codacy.com/vevo-codacy-legacy-systems-coverage/">Vev</a><a href="https://blog.codacy.com/vevo-codacy-legacy-systems-coverage/" target="_blank" rel="noreferrer noopener">o followed this strategy!</a></p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":5315,"sizeSlug":"large","linkDestination":"none","tdCaptionAlign":"https://blog.codacy.com/wp-content/uploads/2022/03/Diff-coverage-metric.png"} -->
<figure class="wp-block-image aligncenter size-large td-caption-align-https://blog.codacy.com/wp-content/uploads/2022/03/Diff-coverage-metric.png"><img src="https://blog.codacy.com/wp-content/uploads/2022/03/Diff-coverage-metric-1024x259.png" alt="Diff coverage metric" class="wp-image-5315"/><figcaption class="wp-element-caption">PR not up to standards </figcaption></figure>
<!-- /wp:image -->

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">The code coverage report is important because it can tell us where we need to focus first. Tools like Codacy can also assist with prioritization by detecting high-risk code.</p>
<!-- /wp:paragraph -->

<!-- wp:buttons -->
<div class="wp-block-buttons"><!-- wp:button {"textColor":"white","align":"center","className":"is-style-round"} -->
<div class="wp-block-button aligncenter is-style-round"><a class="wp-block-button__link has-white-color has-text-color wp-element-button" href="https://www.codacy.com/?utm_source=blog&amp;utm_medium=website&amp;utm_campaign=coverage-types" target="_blank" rel="noreferrer noopener">Get started for free</a></div>
<!-- /wp:button --></div>
<!-- /wp:buttons -->

<!-- wp:heading {"level":1} -->
<h1><strong>Conclusion</strong></h1>
<!-- /wp:heading -->

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">A well-tested codebase is usually (but not always) a well-structured codebase. This means it will be easier for developers to modify the code or add new features. The developers will also feel safer, as a good (automated) test suite provides a safety net for changes.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">For most software, 80%-90% code coverage is an excellent score. Tools like <a href="https://www.codacy.com/?utm_source=blog&amp;utm_medium=website&amp;utm_campaign=coverage-types" target="_blank" rel="noreferrer noopener">Codacy</a> can help you visualize your score and point out files and lines of code that need more tests, allowing you to be more confident about your code quality.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">However, remember that, as Edsger Dijkstra, an early contributor to software engineering development, eloquently stated: <em>Testing can only show the presence of errors, not their absence.</em></p>
<!-- /wp:paragraph -->