簡體   English   中英

如何從 Visual Studio 2022 社區版的單元測試中獲取代碼覆蓋率?

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

我已經下載了最新的 VS2022 v17.1 社區版,它沒有內置代碼覆蓋。 我習慣了企業版,我能找到的只是社區版的付費選項。

是否可以免費在 VS2022 社區版中進行代碼覆蓋?

在此處輸入圖像描述

看來我走運了! XUnit 測試項目帶有一個 NuGet 插件Coverlet.collector

在此處輸入圖像描述

這不需要安裝在任何項目中,您需要做的就是運行我在 Powershell 腳本中制作的這些步驟:

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

# 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/

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

# Open the Code Coverage HTML Report
(& "$dir/coveragereport/index.html")

結果還不錯:

在此處輸入圖像描述

您可以向下鑽取以查看突出顯示的線路覆蓋范圍,它不如企業版強大或集成:

在此處輸入圖像描述

您擁有使用 VS 2022 的 Fine Code Coverage,您可以在此處訪問它https://github.com/FortuneN/FineCodeCoverage/releases並單擊 2022 文件。

之后,它只是您安裝在計算機上的一個插件,它可用於每個項目,而無需逐個項目添加它。

我在使用 Visual Studio 擴展時遇到了一些問題,所以我最終使用了我最好的朋友命令行。

您可以使用Microsoft 的dotnet-coveragedanielpalme dotnet-reportgenerator-globaltool

我相信這應該適用於任何.Net核心運行時和VS版本,也適用於CI服務器(我已經測試過.Net 5)

  • 安裝(以管理員身份運行)
dotnet tool install -g dotnet-coverage
dotnet tool install -g dotnet-reportgenerator-globaltool
  • 使用 XML output 格式運行測試:
dotnet-coverage collect -f xml -o coverage.xml dotnet test <solution/project>
  • 生成 html 報告
reportgenerator -reports:coverage.xml -targetdir:.\report -assemblyfilters:+MyTestedAssembly.dll
  • 打開report\index.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM