前言在做单元测试时,代码覆盖率可以作为我们衡量代码质量的一个指标,本章我们将使用Azure DevOps帮助我们生成代码覆盖率的结果.Azure DevOps构建管道还是具有代码覆盖率选项的,在Visual Studio测试平台在已经集成了Coverlet格式的数据收集器,它其实并不难,它是可以开箱即用的。获取Coverlet格式报告几乎都是可以拿命令行参数去解决的。 在单元测试项目中需要引入nuget包coverlet.collector,当然只需要在单元测试项目中引用他,下面这个代码片段是单元测试模板自动生成的,我只是引入了一个我自己的类库。 <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netcoreapp3.1</TargetFramework> <IsPackable>false</IsPackable> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.6.1" /> <PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3"> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <PrivateAssets>all</PrivateAssets> </PackageReference> <PackageReference Include="coverlet.collector" Version="1.3.0"> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <PrivateAssets>all</PrivateAssets> </PackageReference> </ItemGroup> <ItemGroup> <ProjectReference Include="..\ClassLibrary1\ClassLibrary1.csproj" /> </ItemGroup> </Project> 如何在Azure DevOps中使用?第一步是在构建之前对项目进行还原nuget包,这会将所有的包拉到构建代理的本地文件夹中. - 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中了解更多的信息 安装报告生成工具 - 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 - task: PublishCodeCoverageResults@1 displayName: 'Publish code coverage' inputs: codeCoverageTool: Cobertura summaryFileLocation: '$(Build.SourcesDirectory)/coverlet/reports/Cobertura.xml' 查看报告 常见问题1.如果在Azure DevOps Linux镜像系统中是不可以的,可能会出现 - task: CmdLine@2 inputs: script: 'echo "##vso[task.prependpath]$HOME/.dotnet/tools"' 2.如何生成覆盖率图标?
|
|
来自: python_lover > 《待分类》