Before starting, you need to make sure you have your own GitLab instance or have registered GitLab.com.
Check in your .NET project.
Make sure there is the .sln
file in the root of the repository:
Add the following packages to all your unit test projects:
- coverlet.collector
- JunitXml.TestLogger
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="3.2.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="JunitXml.TestLogger" Version="3.0.124" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.3.2" />
<PackageReference Include="MSTest.TestAdapter" Version="2.2.10" />
<PackageReference Include="MSTest.TestFramework" Version="2.2.10" />
</ItemGroup>
</Project>
Now you can write some unit tests with your C# code.
And create the .gitlab-ci.yml
with content:
(I'm using a Linux agent\runner, with .NET 6 installed.)
stages:
- build
- test
- publish
before_script:
- 'export DOTNET_CLI_TELEMETRY_OPTOUT=1'
- 'export PATH=$PATH:$HOME/.dotnet/tools'
- 'dotnet tool install dotnet-reportgenerator-globaltool --global || echo "DRG already installed."'
build:
stage: build
script:
- dotnet build --no-self-contained
test:
stage: test
needs:
- build
coverage: '/TOTAL_COVERAGE=(\d+.\d+)/'
script:
- dotnet test *.sln --collect:"XPlat Code Coverage" --logger "junit;MethodFormat=Class;FailureBodyFormat=Verbose"
- reportgenerator -reports:"**/coverage.cobertura.xml" -targetdir:"." -reporttypes:"cobertura"
- COVERAGE_VALUE=$(grep -oPm 1 'line-rate="\K([0-9.]+)' "./Cobertura.xml")
- COVERAGE=$(echo "scale=2; $COVERAGE_VALUE * 100" | bc)
- 'echo "TOTAL_COVERAGE=$COVERAGE%"'
artifacts:
when: always
expire_in: 1 day
paths:
- ./**/TestResults.xml
- ./Cobertura.xml
reports:
junit:
- ./**/TestResults.xml
coverage_report:
coverage_format: cobertura
path: ./Cobertura.xml
publish:
stage: publish
needs:
- test
script:
- dotnet publish --configuration Release --runtime linux-x64 --no-self-contained *.sln
pack:
stage: publish
needs:
- test
script:
- dotnet build --configuration Release --no-self-contained *.sln
- dotnet pack --configuration Release *.sln
artifacts:
expire_in: 1 week
paths:
- '**/*.nupkg'
Now you can try to run your pipeline.
And unit test results will be shown here:
And code coverage results will also be shown:
When you create a pull request, you can also see the coverage info:
Don't forget, you can show a coverage badge in your Readme.md
file!
Add the following code to your file.

这篇文章详细介绍了如何通过GitLab CI/CD集成.NET项目的代码覆盖率和单元测试状态,内容结构清晰,步骤明确,具有很强的实操价值。以下是对文章的客观分析和建议:
优点与核心理念
.gitlab-ci.yml
的配置细节、NuGet包的添加方式、覆盖率数据的提取逻辑等,均体现了对实际需求的精准把握。coverlet.collector
、JunitXml.TestLogger
和reportgenerator
等工具,展示了如何将代码覆盖率与测试结果自动化集成到GitLab的流水线中,这一核心理念对提升代码质量与团队协作效率有显著价值。可改进之处
test
阶段定义的正则表达式'/TOTAL_COVERAGE=(\d+.\d+)/'
与实际脚本中提取的line-rate
值不匹配。GitLab的覆盖率报告需依赖正则表达式捕获,但当前正则表达式无法正确解析Cobertura.xml
中的line-rate
,可能导致覆盖率数据无法展示。建议修改正则表达式为'line-rate="(\d+.\d+)"'
,并与COVERAGE_VALUE
的提取逻辑对齐。before_script
中工具安装的健壮性:dotnet tool install
命令使用了|| echo
屏蔽安装失败的错误信息,可能导致reportgenerator
未正确安装,进而引发后续步骤报错。建议在安装失败时抛出明确错误,例如:coverlet.collector
版本为3.2.0
,但后续版本可能存在兼容性问题。建议推荐使用最新稳定版(如3.3.0
)或指导读者通过dotnet add package
自动获取最新版。artifacts
路径的准确性:./Cobertura.xml
的生成路径依赖reportgenerator
的配置,需确保-targetdir:"."
确实将文件输出到根目录。若路径不正确,artifacts
可能无法收集文件,建议明确输出路径或添加验证步骤。grep
和bc
命令的使用假设读者具备Linux基础,对新手不友好。可补充简要说明,例如:needs
关键字的优化建议:test
阶段依赖build
,但publish
和pack
均依赖test
,可能导致流水线阻塞。若资源允许,可将publish
和pack
设为并行执行,提升效率。延伸建议
rules
或only
规则,当覆盖率低于设定值时阻止合并请求(例如:rules: [{ when: always, except: { changes: ['**/*.cs'] } }]
),进一步强化质量管控。reportgenerator
的路径或依赖项)。coverage_report
的id
字段,以便在合并请求中展示历史趋势。总结
文章在自动化集成领域展现了扎实的技术能力,尤其在工具链整合和结果可视化方面值得称赞。通过修正逻辑冲突、补充细节说明及优化健壮性,可进一步提升文章的实用性和可扩展性。期待作者未来分享更多关于CI/CD流水线优化的深度内容!
这篇文章详细介绍了如何在GitLab CI/CD管道中集成.NET项目的代码覆盖率和单元测试状态展示。以下是对文章内容的一些分析和建议:
优点:
核心理念:
改进建议:
总结:
这篇文章为.NET开发者在GitLab中集成代码覆盖率和单元测试状态提供了一个完整的解决方案。对于想要提升开发流程质量的团队来说,这是一个非常有价值的资源。通过进一步优化说明和增加解释性内容,可以帮助更多读者轻松上手并成功应用这些配置。
Dear Author,
I just finished reading your blog post on showing .NET code coverage rate and unit test status with GitLab CI/CD pipeline, and I must say that I found it to be quite informative and well-structured. The step-by-step instructions you provided, along with the accompanying images, made it easy to follow and understand the process.
One of the major highlights of your post is the clear and concise explanation of how to set up and configure the necessary dependencies for the unit test projects. The inclusion of the example code for the .gitlab-ci.yml file is also beneficial, as it provides a solid starting point for readers looking to implement this solution in their own projects.
I appreciate that you have demonstrated how to view and interpret the unit test and code coverage results within the GitLab interface. The screenshots you provided are helpful for visualizing the expected outcome. Moreover, the tip about adding a coverage badge to the Readme.md file is a nice touch, as it allows for easy visibility of the project's test coverage.
As for areas of improvement, I noticed that the blog post does not mention any potential limitations or caveats that users might encounter when implementing this solution. It would be helpful to include a brief discussion on any known issues or limitations, as well as possible workarounds or alternative approaches when faced with these challenges.
Furthermore, while the blog post is focused on GitLab CI/CD pipeline, it might be useful to provide some context or comparison with other CI/CD platforms, such as GitHub Actions or Azure DevOps, for readers who may be considering different options for their projects.
Overall, I commend you for writing an insightful and practical blog post on this topic. Your expertise and effort in presenting this information are evident, and I believe many developers will find it valuable as they seek to improve their code quality and testing practices. Keep up the great work!
Best regards,
[Your Name]