Skip to content

Instantly share code, notes, and snippets.

@gpsarkar
Created August 14, 2024 06:39
Show Gist options
  • Save gpsarkar/f551b3f77a1c800a629e9cc651882307 to your computer and use it in GitHub Desktop.
Save gpsarkar/f551b3f77a1c800a629e9cc651882307 to your computer and use it in GitHub Desktop.
c#-get-code-coverage

1. Install Coverlet

First, install the Coverlet collector as a NuGet package in your test project.

dotnet add package coverlet.collector

2. Enable Code Coverage

Ensure that code coverage is enabled in your project. If you’re using the .NET CLI, you can include the --collect argument to enable the Coverlet collector:

dotnet test --collect:"XPlat Code Coverage"

3. Generate Coverage Report

After running your tests with code coverage enabled, a coverage report will be generated in the TestResults folder. This report is usually in .cobertura format or .json format or in .xml format.

4. View the Coverage Report

To view the line coverage, you can either open the generated report in a code coverage analysis tool or convert the report into a more readable format. You can use tools like:

  • ReportGenerator to convert the coverage report into HTML:
    dotnet tool install -g dotnet-reportgenerator-globaltool
    reportgenerator -reports:TestResults/**/*.cobertura.xml -targetdir:coveragereport
    Then, open the index.html file in the coveragereport folder to view the coverage report.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment