前言
在做單元測試時,代碼覆寫率可以作為我們衡量代碼品質的一個名額,本章我們将使用Azure DevOps幫助我們生成代碼覆寫率的結果.Azure DevOps建構管道還是具有代碼覆寫率選項的,在Visual Studio測試平台在已經內建了Coverlet格式的資料收集器,它其實并不難,它是可以開箱即用的。擷取Coverlet格式報告幾乎都是可以拿指令行參數去解決的。
在單元測試項目中需要引入nuget包coverlet.collector,當然隻需要在單元測試項目中引用他,下面這個代碼片段是單元測試模闆自動生成的,我隻是引入了一個我自己的類庫。
netcoreapp3.1falseruntime; build; native; contentfiles; analyzers; buildtransitiveallruntime; build; native; contentfiles; analyzers; buildtransitiveall
如何在Azure DevOps中使用?
第一步是在建構之前對項目進行還原nuget包,這會将所有的包拉到建構代理的本地檔案夾中.
還原項目包(dotnet restore)
- task: DotNetCoreCLI@2
displayName: 'dotnet restore'
inputs:
command: restore
建構項目(dotnet build)
- task: DotNetCoreCLI@2
displayName: 'dotnet build'
inputs:
command: build
運作單元測試,其實上面的管道任務都是非常簡單的,但是對于單元測試,我們需要設定dotnet cli将測試結果進行收集,搜集為cobertura格式,這是通過指令行參數來完成的。
正如下所示:
運作單元測試
- task: DotNetCoreCLI@2
displayName: 'dotnet test'
inputs:
command: test
projects: '**/XUnitTestProject1.csproj'
arguments: '--configuration $(BuildConfiguration) --collect "XPlat Code coverage" -- RunConfiguration.DisableAppDomain=true'
當然我們可以在coverlet中了解更多的資訊https://discoverdot.net/projects/coverlet
安裝報告生成工具
- task: DotNetCoreCLI@2
displayName: Install ReportGenerator Global Tool
inputs:
command: custom
custom: tool
arguments: install dotnet-reportgenerator-globaltool -g
使用reportgenerator工具生成報告
- script: 'reportgenerator -reports:$(Agent.TempDirectory)/**/coverage.cobertura.xml -targetdir:$(Build.SourcesDirectory)/coverlet/reports -reporttypes:"Cobertura"'
displayName: 'Create reports'
代碼報告釋出到Azure DevOps
最後這一步做的是将剛才生成的所有資訊上傳到Azure DevOps管道,這樣我們就可以在Azure DevOps Ui中檢視覆寫率的相關資訊了。
- task: PublishCodeCoverageResults@1
displayName: 'Publish code coverage'
inputs:
codeCoverageTool: Cobertura
summaryFileLocation: '$(Build.SourcesDirectory)/coverlet/reports/Cobertura.xml'
檢視報告
執行建構管道後,結果将在建構的“代碼覆寫率報告”頁籤中可見。

常見問題
- task: CmdLine@2
inputs:
script: 'echo "##vso[task.prependpath]$HOME/.dotnet/tools"'
- 覆寫率圖示:https://img.shields.io/azure-devops/coverage/{組織名稱}/{項目名稱}/2/{分支}
【Azure DevOps系列】Azure DevOps生成代碼覆寫率 - 單元測試個數:https://img.shields.io/azure-devops/tests/{組織名稱}/{項目名稱}/2/{分支}
【Azure DevOps系列】Azure DevOps生成代碼覆寫率