Introduction

This lesson is a practical implementation of the theory taught in the “Unit Test Coverage: Concepts and Techniques” lesson.

Before diving into more practical aspects, let’s briefly recap unit test coverage theory. Test coverage is a measure of the degree to which the application code is executed when test code is run. The test code may enhance test coverage by increasing the branch coverage of the application code. Branch coverage is the ratio of the number of executed branches in an application’s code to the total number of branches in the code. Control structures include selection statements and iteration statements. Selection statements include the if, if else, and switch statements. Iteration statements include the do, for, for each, and while statements.

You can think of branch coverage qualitatively and quantitatively. Its quantitative measurement is given by the following equation:

Branch coverage=Branches traversedTotal number of branches\mathsf{Branch\ coverage} = \dfrac{\mathsf{Branches\ traversed}}{\mathsf{Total\ number\ of\ branches}}

If the test code invokes a branch coverage of 100%, we know that our test cases are comprehensive. However, this doesn’t guarantee that the code caters to all behavior. Testing all the application code is not necessary given that some application code is trivial from a testing perspective. For example, trivial application code includes entities, class properties, and repositories in a web application.

Setting up code coverage tools as part of NUnit

In this section, we’ll go through how to use the AltCover coverage tool. AltCover is an instrumenting coverage tool for .NET (Framework 2.0+ and .NET Core).

Setting up AltCover

We will set up two code coverage tools that work hand in hand:

  • AltCover
  • AltCover.Visualizer

The former runs the code coverage process and the latter outputs the results to the user.

Setting up application and test code

Set up some application code under Project and test code under ProjectTest shown below. Ensure that the directory path to the project contains as few characters as possible. Otherwise, our code coverage tools may not work. Run your tests on your local environment to ensure that all three tests pass. If you click “Run” below, you’ll see that all three tests pass.

Get hands-on with 1400+ tech skills courses.