如何从 Visual Studio 2022 社区版的单元测试中获取代码覆盖率?
Posted
技术标签:
【中文标题】如何从 Visual Studio 2022 社区版的单元测试中获取代码覆盖率?【英文标题】:How to get Code Coverage from Unit Tests in Visual Studio 2022 Community Edition? 【发布时间】:2022-01-16 03:31:19 【问题描述】:我已经下载了最新的 VS2022 v17.1 社区版,它没有内置代码覆盖。我已经习惯了企业版,我能找到的只是社区版的付费选项。
是否可以免费在 VS2022 社区版中进行代码覆盖?
【问题讨论】:
【参考方案1】:您拥有使用 VS 2022 的 Fine Code Coverage,您可以在此处访问它 https://github.com/FortuneN/FineCodeCoverage/releases,点击2022文件。
之后,它只是您安装在计算机上的一个插件,它可用于每个项目,而无需逐个项目添加。
【讨论】:
【参考方案2】:看来我很幸运! XUnit 测试项目带有一个 NuGet 插件Coverlet.Collector:
这不需要安装在任何项目中,您只需运行我在 Powershell 脚本中制作的这些步骤:
ExecCodeCoverage.ps1
# PURPOSE: Automates the running of Unit Tests and Code Coverage
# REF: https://***.com/a/70321555/495455
# 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\0f26f16d-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")
把它放在TestProject中:
结果非常好(免费):
您可以深入查看突出显示的线路覆盖范围,它只是不如企业版强大或集成:
我也更新了脚本以支持历史记录:
【讨论】:
以上是关于如何从 Visual Studio 2022 社区版的单元测试中获取代码覆盖率?的主要内容,如果未能解决你的问题,请参考以下文章
在 Visual Studio 2015 社区 C++ 中,如何修复警告 C4838:从 'unsigned int' 到 'int' 的转换需要缩小转换