Visual Studio 2022 Community Edition 如何从单元测试中获取代码覆盖率?

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

我已经下载了最新的 VS2022 v17.1 社区版,但它没有内置代码覆盖率。我习惯了企业版,我能找到的只有社区版的付费选项。

是否可以在 VS2022 社区版中免费进行代码覆盖?

服务器构建历史方式...

XUnit 测试项目带有 NuGet 插件Coverlet.Collector:

这不需要在任何项目中安装,您需要做的就是运行我已经制作成Powershell脚本的这些步骤:

ExecCodeCoverage.ps1

# PURPOSE: Automates the running of Unit Tests and Code Coverage
# REF: 

# 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 (this is an NuGet included with XUnit Test Projects)
$output = [string] (& dotnet test --collect:"XPlat Code Coverage" 2>&1)
Write-Host "Last Exit Code: $lastexitcode"
Write-Host $output

# Extract the GUID from the Output eg, 
#"Attachments:   E:\Dev\XYZ\src\XYZTestProject\TestResults[=10=]f26f16d-bbe8-463b-856b-6d4fbee673bd\coverage.cobertura.xml Passed!"  

$i = $output.LastIndexOf("TestResults") + 11
$j = $output.LastIndexOf("coverage")
$cmdGuid = $output.SubString($i,$j - $i - 1)
Write-Host $cmdGuid 

# 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/TestResults/$cmdGuid/coverage.cobertura.xml" -targetdir:"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")
}

将其放入测试项目中:

效果还不错(免费):

您可以向下钻取以查看突出显示的线路覆盖范围,它只是不如企业版强大或集成:

我更新了脚本以支持历史记录:

你有与 VS 2022 一起使用的 Fine Code Coverage,你可以在这里访问它 https://github.com/FortuneN/FineCodeCoverage/releases 然后点击 2022 文件。

之后,它只是一个安装在计算机上的插件,每个项目都可以使用它,而无需逐个项目地添加它。