Unit Test (4) --- Code Coverage

Note: this article is published on 08/24/2024.

This series of articles will discuss Unit Test

This article will discuss the basic of Unit Test.

A - Introduction

Code coverage is a metric that can help you understand how much of your source is tested. It's a very useful metric that can help you assess the quality of your test suite, and we will see here how you can get started with your projects. 

This article includes:

  • A - Introduction
  • B - How Code Coverage is Calculated
  • C - Visual Studio with Code Coverage
  • D - SQL Server SSMS with Code Coverage

B - How Code Coverage is Calculated


Code coverage tools will use one or more criteria to determine how your code was exercised or not during the execution of your test suite. The common metrics that you might see mentioned in your coverage reports include:

  • Function coverage: how many of the functions defined have been called.
  • Statement coverage: how many of the statements in the program have been executed.
  • Branches coverage: how many of the branches of the control structures (if statements for instance) have been executed.
  • Condition coverage: how many of the boolean sub-expressions have been tested for a true and a false value.
  • Line coverage: how many of lines of source code have been tested.

These metrics are usually represented as the number of items actually tested, the items found in your code, and a coverage percentage (items tested / items found).

These metrics are related, but distinct. In the trivial script below, we have a Javascript function checking whether or not an argument is a multiple of 10. We'll use that function later to check whether or not 100 is a multiple of 10. It'll help understand the difference between the function coverage and branch coverage.

C - Visual Studio with Code Coverage [ref]

Unit Test in Visual Studio 2022:

Requirements for Code Coverage:

The code coverage feature is available only in Visual Studio Enterprise edition.

in Visual Studio 2022: Professional Edition --- no this feature:

By click Analyze Code Coverage for All Test:in Visual Studio 2022 Enterprise:

View the tested code by highlighted in color:

D - SQL Server SSMS with Code Coverage [ref]

Test Coverage with SQL Cover --- SQL Test includes SQLCover, a code coverage tool written by Ed Elliott.

Enabling Code Coverage --- To enable code coverage on a series of tests, make sure the Code Coverage checkbox is checked before running the tests.

You can now run your tests. When the run is complete, you will see a tab to the right of the test output giving you the overall coverage level for the tests that have been run. The tab contains a full breakdown of coverage by function / procedure, and highlights the statements actually executed in each function / procedure during the test run:

References:


Similar Articles