wasAsked.

how do you implement code coverage for dotnet app

PwC · Full Stack Developer · technical

Published

Year not specified · .NET

Community answers

Posted by wasAsked editorial collection

Code coverage measures which lines and branches your tests execute. In .NET it is usually collected with Coverlet and reported with ReportGenerator. 1. Collect coverage The xUnit and NUnit project templates already include the coverlet.collector package. Run: dotnet test --collect:"XPlat Code Coverage" --results-directory ./TestResults This produces a coverage.cobertura.xml file per test project. Alternatives: - coverlet.msbuild: dotnet test /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura - Microsoft's own coverage tooling: dotnet test --collect "Code Coverage" (and dotnet-coverage), which also works with Microsoft.Testing.Platform. - Visual Studio Enterprise and JetBrains dotCover have built-in coverage views. 2. Generate a readable report dotnet tool install -g dotnet-reportgenerator-globaltool reportgenerator -reports:"TestResults/**/coverage.cobertura.xml" -targetdir:"coverage-report" -reporttypes:Html 3. Exclude code that should not count - Generated code, migrations, Program.cs bootstrap, DTOs: use [ExcludeFromCodeCoverage] or Coverlet settings in a .runsettings file (Exclude, ExcludeByFile, ExcludeByAttribute). 4. Integrate with CI - Azure Pipelines: the PublishCodeCoverageResults task shows coverage in the build summary. - GitHub Actions: publish the report as an artifact or comment on the pull request; services such as Codecov or SonarQube/SonarCloud track coverage over time. - Optionally enforce a threshold (Coverlet /p:Threshold=80, or a quality gate on new code only). 5. Use the number wisely - Coverage shows what is not tested; it does not prove that tests are meaningful. 100% coverage with weak assertions is still risky. - Focus on business-critical code and branch coverage, and require tests for new code rather than chasing a global percentage. - Combine with mutation testing (Stryker.NET) when you want to know whether tests actually detect bugs.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics