Code coverage
suggest changeCode coverage measures which parts of your code ran while the tests ran. A coverage tool instruments the compiled assemblies, runs the tests, records which lines and branches executed, and writes a report.
The main numbers are:
- line coverage: percentage of executable lines that ran at least once
- branch coverage: percentage of branch outcomes (both sides of an
if, every arm of aswitch) that were taken - method coverage: percentage of methods that were called at all
Coverage is good at one thing: showing code that no test touches. A line that never runs can't be checked by any assertion. It's bad at telling you whether your tests are any good: a test that calls everything and asserts nothing gets 100%.
In .NET there are two coverage engines:
| Microsoft Code Coverage | Coverlet | |
|---|---|---|
| MTP package | Microsoft.Testing.Extensions.CodeCoverage |
coverlet.MTP |
| VSTest package | Microsoft.NET.Test.Sdk (built in) |
coverlet.collector |
| enable | --coverage |
--coverlet |
| formats | .coverage, xml, cobertura |
json, cobertura, lcov, opencover |
| fail on low coverage | no | --coverlet-threshold |
Both are free, open source and cross-platform. Examples use xUnit v3 on .NET 10 with Microsoft.Testing.Platform (MTP), set up as in Unit testing.
The code under test
A small pricing library:
namespace Shop;
public static class Pricing
{
public static decimal Discount(decimal total, bool isMember)
{
if (total <= 0)
throw new ArgumentOutOfRangeException(nameof(total));
decimal rate = 0m;
if (total >= 100m)
rate = 0.10m;
if (isMember && total >= 50m)
rate += 0.05m;
return Math.Round(total * rate, 2);
}
public static string Tier(decimal total) => total switch
{
< 50m => "bronze",
< 200m => "silver",
_ => "gold",
};
}
It's in Shop/Pricing.cs, line 1 is namespace Shop;. The reports below refer to line numbers in this file.
And a first, incomplete set of tests:
using Shop;
public class PricingTests
{
[Fact]
public void BigOrderGetsTenPercent() =>
Assert.Equal(15.00m, Pricing.Discount(150m, isMember: false));
[Fact]
public void SmallOrderGetsNothing() =>
Assert.Equal(0m, Pricing.Discount(20m, isMember: false));
[Fact]
public void SilverTier() =>
Assert.Equal("silver", Pricing.Tier(120m));
}
Collecting coverage with Microsoft Code Coverage
Add the Microsoft.Testing.Extensions.CodeCoverage package to the test project:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<OutputType>Exe</OutputType>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="xunit.v3" Version="4.0.2" />
<PackageReference Include="Microsoft.Testing.Extensions.CodeCoverage" Version="18.12.0" />
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
<ProjectReference Include="..\Shop\Shop.csproj" />
</ItemGroup>
</Project>
The solution has a global.json that switches dotnet test to MTP:
{
"test": {
"runner": "Microsoft.Testing.Platform"
}
}
Run the tests with --coverage:
dotnet test --coverage
Running tests from C:\src\Shop\Shop.Tests\bin\Debug\net10.0\Shop.Tests.dll (net10.0|x64)
C:\src\Shop\Shop.Tests\bin\Debug\net10.0\Shop.Tests.dll (net10.0|x64) passed (1s 898ms)
In process file artifacts produced:
- C:\src\Shop\TestResults\7e5076c1-5f2a-4b2e-8e25-a8877b931a6d.coverage
Test run summary: Passed!
total: 3
failed: 0
succeeded: 3
skipped: 0
duration: 3s 906ms
The default .coverage format is binary. Visual Studio opens it, but almost nothing else does. Ask for Cobertura XML instead, the format every CI system and report tool understands:
dotnet test --coverage --coverage-output-format cobertura --coverage-output coverage.cobertura.xml
The file goes to TestResults/coverage.cobertura.xml (--coverage-output with just a file name puts it in the --results-directory, which defaults to TestResults). Without --coverage-output you get a GUID name.
Only your code is measured. The test assembly and the xUnit and .NET assemblies are left out by default.
Reading a Cobertura report
The top of the report has the totals:
<coverage line-rate="0.75" branch-rate="0.5833333333333334" complexity="12" version="1.9"
timestamp="1792266402" lines-covered="12" lines-valid="16"
branches-covered="7" branches-valid="12">
Then each class lists every line with a hit count, and branch lines with their condition coverage:
<line number="7" hits="1" branch="True" condition-coverage="50% (1/2)">
<conditions>
<condition number="0" type="jump" coverage="50%" />
</conditions>
</line>
<line number="8" hits="0" branch="False" />
Raw XML is hard to read, so here's a small file-based program (dotnet run uncovered.cs -- <file>) that prints the totals and lists the lines that need attention. It also takes an optional minimum line coverage and returns exit code 1 when coverage is lower, which is handy in CI:
using System.Globalization;
using System.Xml.Linq;
var root = XDocument.Load(args[0]).Root!;
double Percent(string attr) =>
double.Parse(root.Attribute(attr)!.Value, CultureInfo.InvariantCulture) * 100;
double lineCoverage = Percent("line-rate");
Console.WriteLine($"line coverage: {lineCoverage:F1}%");
Console.WriteLine($"branch coverage: {Percent("branch-rate"):F1}%");
foreach (var cls in root.Descendants("class"))
{
string file = Path.GetFileName(cls.Attribute("filename")!.Value);
// the class-level <lines> lists every line of the class once
foreach (var line in cls.Element("lines")!.Elements("line"))
{
string number = line.Attribute("number")!.Value;
int hits = int.Parse(line.Attribute("hits")!.Value);
string? cond = line.Attribute("condition-coverage")?.Value;
if (hits == 0)
Console.WriteLine($" {file}:{number} not executed");
else if (cond is not null && !cond.StartsWith("100%"))
Console.WriteLine($" {file}:{number} partial branch {cond}");
}
}
// optional second argument: minimum line coverage in percent
if (args.Length > 1)
{
double min = double.Parse(args[1], CultureInfo.InvariantCulture);
if (lineCoverage < min)
{
Console.Error.WriteLine($"FAIL: line coverage {lineCoverage:F1}% is below {min}%");
return 1;
}
}
return 0;
Rates are parsed with CultureInfo.InvariantCulture because Cobertura always writes 0.75. A plain double.Parse breaks on machines whose culture uses a comma as the decimal separator.
dotnet run uncovered.cs -- TestResults/coverage.cobertura.xml 80
line coverage: 75.0%
branch coverage: 58.3%
Pricing.cs:7 partial branch 50% (1/2)
Pricing.cs:8 not executed
Pricing.cs:13 partial branch 50% (2/4)
Pricing.cs:14 not executed
Pricing.cs:19 partial branch 50% (2/4)
Pricing.cs:21 not executed
Pricing.cs:23 not executed
FAIL: line coverage 75.0% is below 80%
Each entry is a missing test:
- lines 7-8: no test passes a total of zero or less, so the
thrownever runs - lines 13-14: no test passes
isMember: true - lines 19-23: the
switchexpression has three arms, onlysilverwas tested
Note that the switch expression counts as one line for branches (line 19) but each arm is its own line for hits.
Filling the gaps
using Shop;
public class PricingTests
{
[Fact]
public void BigOrderGetsTenPercent() =>
Assert.Equal(15.00m, Pricing.Discount(150m, isMember: false));
[Fact]
public void SmallOrderGetsNothing() =>
Assert.Equal(0m, Pricing.Discount(20m, isMember: false));
[Fact]
public void MemberGetsExtraFivePercent() =>
Assert.Equal(3.00m, Pricing.Discount(60m, isMember: true));
[Fact]
public void ZeroTotalThrows() =>
Assert.Throws<ArgumentOutOfRangeException>(() => Pricing.Discount(0m, isMember: false));
[Theory]
[InlineData(10, "bronze")]
[InlineData(120, "silver")]
[InlineData(500, "gold")]
public void Tiers(decimal total, string expected) =>
Assert.Equal(expected, Pricing.Tier(total));
}
line coverage: 100.0%
branch coverage: 100.0%
100% doesn't mean fully tested
Look at what's still missing:
- No test calls
DiscountwithisMember: trueand a total below 50. Branch coverage is 100% anyway. - No test uses a total of exactly 50 or 100, the boundaries of the rules.
Branch coverage is measured on the compiled IL, not on the conditions in your source. isMember && total >= 50m compiles to two conditional jumps: one on isMember, and one on the combined result. isMember: false takes the "false" side of both, the member test takes the "true" side of both, and all 4 outcomes are covered. The isMember: true, total: 30 combination was never checked.
To prove it, change total >= 50m to total > 50m (an off-by-one bug) and run again:
Test run summary: Passed!
line coverage: 100.0%
branch coverage: 100.0%
All tests pass, coverage is still 100%, and members spending exactly 50 lose their discount. Coverage tells you where tests are missing. It can't tell you that the tests you have check the right things. For that you need boundary tests (see Parameterized tests) and code review. Mutation testing tools like Stryker.NET go further: they make changes like >= to > and report the ones no test catches.
Excluding code from coverage
Some code isn't worth testing: debugging helpers, generated code, database migrations. Including it drags the numbers down and hides the uncovered code that matters.
Suppose the project grows two such files:
namespace Shop;
public static class DebugDump
{
public static void Print(decimal total)
{
Console.WriteLine($"total={total}");
Console.WriteLine($"tier={Pricing.Tier(total)}");
Console.WriteLine($"discount={Pricing.Discount(total, false)}");
}
}
namespace Shop.Migrations;
public static class M001_Init
{
public static string Up() => "CREATE TABLE orders (id INT, total DECIMAL)";
public static string Down() => "DROP TABLE orders";
}
line coverage: 69.6%
branch coverage: 100.0%
DebugDump.cs:6 not executed
DebugDump.cs:7 not executed
DebugDump.cs:8 not executed
DebugDump.cs:9 not executed
DebugDump.cs:10 not executed
M001_Init.cs:5 not executed
M001_Init.cs:6 not executed
[ExcludeFromCodeCoverage]
The attribute from System.Diagnostics.CodeAnalysis works on classes, structs, methods, constructors, properties and events, and both coverage engines respect it:
using System.Diagnostics.CodeAnalysis;
namespace Shop;
[ExcludeFromCodeCoverage(Justification = "debugging helper, not shipped behavior")]
public static class DebugDump
{
public static void Print(decimal total)
{
Console.WriteLine($"total={total}");
Console.WriteLine($"tier={Pricing.Tier(total)}");
Console.WriteLine($"discount={Pricing.Discount(total, false)}");
}
}
Justification (available since .NET 5) is optional, but it tells the next reader why the code was excluded. Coverlet also excludes code marked [GeneratedCode] or [CompilerGenerated] by default.
A settings file
To exclude code without changing it, use a settings file and pass it with --coverage-settings:
<?xml version="1.0" encoding="utf-8"?>
<Configuration>
<Format>cobertura</Format>
<CodeCoverage>
<Sources>
<Exclude>
<Source>.*/Migrations/.*</Source>
</Exclude>
</Sources>
</CodeCoverage>
</Configuration>
dotnet test --coverage --coverage-settings coverage.settings.xml --coverage-output coverage.cobertura.xml
line coverage: 100.0%
branch coverage: 100.0%
Entries are regular expressions matched against the full path of the source file. Write the separator as / even on Windows: in my test on Windows, .*/Migrations/.* matched and .*\\Migrations\\.* didn't. The same <CodeCoverage> section also has <ModulePaths>, <Functions> and <Attributes>, each with <Include> and <Exclude> lists, to filter by assembly, by method name or by attribute.
<Format> sets the output format, so --coverage-output-format isn't needed with this file.
Collecting coverage with Coverlet
Coverlet is the other popular engine. For MTP, replace the Microsoft package with coverlet.MTP:
<PackageReference Include="coverlet.MTP" Version="10.1.0" />
and run with --coverlet:
dotnet test --coverlet --coverlet-output-format cobertura
The report goes to TestResults/coverage.cobertura.<timestamp>.xml. Without --coverlet-output-format you get both json and cobertura. When several test projects write to the same directory, --coverlet-file-prefix gives each report its own name.
The numbers are the same as with Microsoft Code Coverage for this project: with the first three tests the report says line-rate="0.75" and 7 of 12 branches covered.
Coverlet's useful extra is a built-in threshold:
dotnet test --coverlet --coverlet-threshold 80 --coverlet-threshold-type line
With the incomplete tests (75% line coverage) all tests pass, but the run fails:
C:\src\Shop\Shop.Tests\bin\Debug\net10.0\Shop.Tests.dll (net10.0|x64) failed (1s 367ms)
Exit code: 14
Test run summary: Failed!
error: 1
total: 3
failed: 0
succeeded: 3
skipped: 0
duration: 6s 072ms
Test run completed with non-success exit code: 14 (see: https://aka.ms/testingplatform/exitcodes)
The terminal doesn't say why. The reason ("Coverage thresholds not met.") is only in the diagnostic log, written with --diagnostic. Keep that in mind when a CI build fails with all tests green.
--coverlet-threshold-type takes line, branch and method, comma-separated (line,branch). The default is line. --coverlet-threshold-stat decides what is compared to the threshold: Minimum (default, every module must pass), Total or Average.
[ExcludeFromCodeCoverage] works the same as with Microsoft Code Coverage. To exclude files, use --coverlet-exclude-by-file "**/Migrations/*.cs" or put the settings in a testconfig.json file in the test project:
{
"platformOptions": {
"Coverlet": {
"format": "cobertura",
"excludeByFile": "**/Migrations/*.cs",
"excludeByAttribute": "ExcludeFromCodeCoverage,GeneratedCodeAttribute,CompilerGeneratedAttribute"
}
}
}
When the config file exists, Coverlet stops adding its default exclusions, so list everything you want excluded. Be careful with --coverlet-exclude "[Assembly]Type" filters too: in my test, adding one made Coverlet also measure the test assembly (including the xUnit assertion code compiled into it), and line coverage dropped to 1.9%. Check the report after changing filters.
On the older VSTest runner, use coverlet.collector and dotnet test --collect:"XPlat Code Coverage", or coverlet.msbuild and dotnet test /p:CollectCoverage=true /p:Threshold=80. See Testing in CI.
HTML reports with ReportGenerator
ReportGenerator turns Cobertura (and other formats) into HTML with your source code colored by coverage. Install it as a local tool so the version is pinned in the repository:
dotnet new tool-manifest
dotnet tool install dotnet-reportgenerator-globaltool
Generate an HTML report and a text summary:
dotnet reportgenerator -reports:TestResults/coverage.cobertura.xml -targetdir:coveragereport -reporttypes:"Html;TextSummary"
coveragereport/Summary.txt for the first, incomplete test run:
Summary
Generated on: 10/17/2026 - 21:46:52
Parser: Cobertura
Assemblies: 1
Classes: 1
Files: 1
Line coverage: 75%
Covered lines: 12
Uncovered lines: 4
Coverable lines: 16
Total lines: 25
Branch coverage: 58.3% (7 of 12)
Covered branches: 7
Total branches: 12
Method coverage: 100% (2 of 2)
Full method coverage: 0% (0 of 2)
Covered methods: 2
Fully covered methods: 0
Total methods: 2
Shop 75%
Shop.Pricing 75%
Open coveragereport/index.html in a browser. Each file is shown with covered lines in green, uncovered lines in red and partially covered branches in yellow. That's the fastest way to see what a test is missing.
-reports accepts globs and several files separated by ;, and merges them. With many test projects, -reports:"**/TestResults/*.cobertura.xml" builds one report for the whole solution. Other useful report types: MarkdownSummaryGithub (for a GitHub Actions job summary), Badges (SVG badges) and lcov.
Merging reports with dotnet-coverage
dotnet-coverage is Microsoft's command line tool for the same coverage engine. It can merge and convert reports:
dotnet tool install dotnet-coverage
dotnet dotnet-coverage merge "TestResults/*.cobertura.xml" -f cobertura -o merged.cobertura.xml
It can also convert .coverage files to Cobertura, but the converted report had no branch data in my test. If you need branch coverage, ask for cobertura when collecting.
Coverage in CI
A GitHub Actions job that collects coverage, publishes a summary on the run page and fails below 80%:
- name: Test with coverage
run: dotnet test --coverage --coverage-output-format cobertura --coverage-output coverage.cobertura.xml
- name: Coverage report
run: |
dotnet tool restore
dotnet reportgenerator "-reports:**/TestResults/coverage.cobertura.xml" -targetdir:coveragereport "-reporttypes:Html;MarkdownSummaryGithub"
cat coveragereport/SummaryGithub.md >> "$GITHUB_STEP_SUMMARY"
- name: Check coverage
run: dotnet run uncovered.cs -- TestResults/coverage.cobertura.xml 80
- uses: actions/upload-artifact@v4
with:
name: coverage-report
path: coveragereport
With Coverlet, --coverlet-threshold replaces the last step.
Practical advice
- Use coverage to find untested code, not as a score. Sort the HTML report by uncovered lines and look at the biggest gaps in important code first.
- Don't chase 100%. The last few percent are usually trivial getters,
ToStringoverrides and "impossible" error paths. Tests for them cost time and add little. - Prefer a threshold that stops regressions over a high fixed target. Set it a little below the current value and raise it as coverage improves.
- Look at branch coverage. Line coverage hides untested
elsesides,?:,??andswitcharms that sit on a line that ran. - Exclude with a reason.
[ExcludeFromCodeCoverage(Justification = "...")]documents the decision. Excluding code only to hit a number defeats the purpose. - Don't run coverage on benchmarks or performance tests. Instrumented code is slower.
Visual Studio Enterprise (Test > Analyze Code Coverage), JetBrains Rider (dotCover) and VS Code with C# Dev Kit (Run Tests with Coverage) show the same data inside the editor, with coverage marks next to each line.