.NET Core項目自動化測試和代碼覆蓋率審查


這篇文章給大家分享一下,如何配置.NET Core項目自動化測試和代碼覆蓋率審查。

基本知識,請參考這里: https://docs.microsoft.com/en-us/dotnet/core/testing/unit-testing-with-dotnet-test

環境准備:

演示項目基於Visual Studio Code,並且安裝如下插件

  1. Coverage Gutters
  2. Coverlet

我有如下的項目結構

本地開發環境運行測試並查看代碼覆蓋率

運行 dotnet test /p:CollectCoverage=true /p:CoverletOutputFormat=lcov /p:CoverletOutput=./lcov.info

點擊狀態欄中的Watch 按鈕

這樣就能快速進入源代碼中查看哪些代碼覆蓋,哪些代碼沒有覆蓋。

下圖紅色標出的代碼是沒有覆蓋到的。

 

配置CI 系統自動測試和計算覆蓋率

我這里用 的是Azure DevOps,希望每次pipeline運行時能了解測試成功率和代碼覆蓋率。

你可以像下面這樣定義Pipeline

 

# ASP.NET

# Build and test ASP.NET projects.

# Add steps that publish symbols, save build artifacts, deploy, and more:

# https://docs.microsoft.com/azure/devops/pipelines/apps/aspnet/build-aspnet-4

 

trigger:

- main

 

pool:

vmImage: 'windows-latest'

 

variables:

solution: '**/*.sln'

buildPlatform: 'Any CPU'

buildConfiguration: 'Release'

 

steps:

- task: NuGetToolInstaller@1

 

- task: NuGetCommand@2

inputs:

restoreSolution: '$(solution)'

 

- task: VSBuild@1

inputs:

solution: '$(solution)'

msbuildArgs: '/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="$(build.artifactStagingDirectory)"'

platform: '$(buildPlatform)'

configuration: '$(buildConfiguration)'

 

- task: DotNetCoreCLI@2

inputs:

command: 'test'

arguments: '--collect "XPlat Code Coverage"'

 

- task: PublishCodeCoverageResults@1

inputs:

codeCoverageTool: 'Cobertura'

summaryFileLocation: '$(Agent.TempDirectory)\*\coverage.cobertura.xml'

 

成功運行后,會看到下面這樣的詳細測試報告

 

還有代碼覆蓋率審查報告

 

通過在Azure DevOps安裝一個插件("Build Quality Checks"),可以根據代碼覆蓋率的數值進行代碼質量審查。例如下圖所示,就是我們規定必須代碼覆蓋率到達60%以上才能編譯通過。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM