.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%以上才能编译通过。

 

posted @   陈希章  阅读(914)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示