How to get Code Coverage from Unit Tests in Visual Studio 2022 Community Edition?
Asked Answered
F

3

41

I've downloaded the latest VS2022 v17.1 Community Edition and it doesn't come with Code Coverage in-built. I'm accustomed to the Enterprise Edition and all I can find is paid options for the Community Edition.

Is it possible to do Code Coverage in VS2022 Community Edition for FREE?

enter image description here

Flitting answered 12/12, 2021 at 6:36 Comment(0)
H
56

You have Fine Code Coverage working with VS 2022, you can access to it here https://github.com/FortuneN/FineCodeCoverage/releases and click on the 2022 file.

After that, it´s just a plugin that you install on your computer and it´s available to every single project without the need to add it project by project.

Update: Now it's available directly from the marketplace, so you can install it from the Extensions Manager or you can download it from marketplace (https://marketplace.visualstudio.com/items?itemName=FortuneNgwenya.FineCodeCoverage2022) and execute it on your computer.

Heiskell answered 16/12, 2021 at 8:57 Comment(4)
This is good and the results are in the View > Other windows > FineCodeCoverage. If anyone has problems see the ReadMe.md - the part about Settings Tools > Options > Fine Code Coverage > AdjacentBuildOutput to true.Flitting
Thanks @JeremyThompson I was having problems getting the async code coverage to work. and this worked.Brave
The disadvantage of this extension is that it does not paint the entire line of covered code.Fanya
@Fanya that's what my answer addresses. It's a guessing game getting code coverage as a % without green/red highlights!Flitting
F
33

XUnit (and NUNIT - see last paragraph) Test Projects come with a NuGet plugin Coverlet.Collector:

enter image description here

This doesn't need to be installed in any project, all you need to do is run these steps that I've made into a Powershell script:

ExecCodeCoverage.ps1

# PURPOSE: Automates the running of Unit Tests and Code Coverage
# REF: https://mcmap.net/q/196420/-how-to-get-code-coverage-from-unit-tests-in-visual-studio-2022-community-edition

# If running outside the test folder
#cd E:\Dev\XYZ\src\XYZTestProject

# This only needs to be installed once (globally), if installed it fails silently: 
dotnet tool install -g dotnet-reportgenerator-globaltool

# Save currect directory into a variable
$dir = pwd

# Delete previous test run results (there's a bunch of subfolders named with guids)
Remove-Item -Recurse -Force $dir/TestResults/

# Run the Coverlet.Collector - REPLACING YOUR SOLUTION NAME!!!
$output = [string] (& dotnet test ../YOURSOLUTIONNAME.sln --collect:"XPlat Code Coverage" 2>&1)
Write-Host "Last Exit Code: $lastexitcode"
Write-Host $output

# Delete previous test run reports - note if you're getting wrong results do a Solution Clean and Rebuild to remove stale DLLs in the bin folder
Remove-Item -Recurse -Force $dir/coveragereport/

# To keep a history of the Code Coverage we need to use the argument: -historydir:SOME_DIRECTORY 
if (!(Test-Path -path $dir/CoverageHistory)) {  
 New-Item -ItemType directory -Path $dir/CoverageHistory
}

# Generate the Code Coverage HTML Report
reportgenerator -reports:"$dir/**/coverage.cobertura.xml" -targetdir:"$dir/coveragereport" -reporttypes:Html -historydir:$dir/CoverageHistory 

# Open the Code Coverage HTML Report (if running on a WorkStation)
$osInfo = Get-CimInstance -ClassName Win32_OperatingSystem
if ($osInfo.ProductType -eq 1) {
(& "$dir/coveragereport/index.html")
}

Put it in the TestProject:

enter image description here

^ Right click Run with Powershell

The results are quite good (for FREE):

enter image description here

You can drill down to see the highlighted line coverage, its just not as powerful or integrated as the Enterprise Edition:

enter image description here

I updated the script to support History as well:

enter image description here


'

NUnit UPDATE: This script works with NUNit as well, simply include these references:

enter image description here

  <ItemGroup>
    <PackageReference Include="coverlet.collector" Version="3.1.2">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="coverlet.collector" Version="3.1.2" />
    <PackageReference Include="GenFu" Version="1.6.0" />
    <PackageReference Include="Moq" Version="4.18.2" />
    <PackageReference Include="NUnit" Version="3.13.3" />
    <PackageReference Include="NUnit3TestAdapter" Version="4.2.1" />
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.3.2" />
    <PackageReference Include="NunitXml.TestLogger" Version="3.0.127" />
    <PackageReference Include="ReportGenerator" Version="5.1.10" />
  </ItemGroup>
Flitting answered 12/12, 2021 at 6:53 Comment(4)
Hi Jeremy, does it work with c++?Zeiger
It works with Visual Studio so it should support all languages: VB.Net, C#, F# and C++ as well.Flitting
can this be added in a build pipeline @JeremyThompson ? We are using bitbucket pipeline and would like to add this and have the result displayed some placeTriplex
Yes and no, the purpose of this answer is to run CodeCoverage on a Server (in your CI/CD pipeline). Notice at the end of the script I detect if its running on a Server and don't show the results, instead you should copy files &/or provide a link to the results in the Build output. The server is running unattended so you don't want it to show the results there otherwise you'd have to login to the Build Agent to see them.Flitting
B
17

I've had some problems with Visual Studio extensions, so I ended up using my very best friend, the command line.

You can do from the command line, using Microsoft's dotnet-coverage and danielpalme dotnet-reportgenerator-globaltool

I believe this should work with any .Net core runtime and VS version, and also on CI servers (I've tested .Net 5)

  • Install (run as admin)
dotnet tool install -g dotnet-coverage
dotnet tool install -g dotnet-reportgenerator-globaltool
  • Run tests with XML output format:
dotnet-coverage collect -f xml -o coverage.xml dotnet test <solution/project>
  • Generate html report
reportgenerator -reports:coverage.xml -targetdir:.\report -assemblyfilters:+MyTestedAssembly.dll
  • Open report\index.html
Beat answered 8/9, 2022 at 13:39 Comment(3)
Is there a VS Code extension for it?Lesley
If you use: -targetdir:%temp%\report your source directory will be unmodifiedQuibbling
@michael-kruglos This would be helpful if you want line coverage #76946538 . If you want to do full coverage analysis in VS Code this might be helpful: #76968176Leesaleese

© 2022 - 2024 — McMap. All rights reserved.