如果熟悉 GIthub 我们经常可以在一些开源项目的 PR 上看到会配置测试的验证以及覆盖率的报告,并且可以强制覆盖率不低于设定的值才可以进行 Merge PR。

1.测试
创建一个 xUnit 单元测试项目。
Class- /// <summary>
- /// Represents a class with methods to perform addition and subtraction operations.
- /// </summary>
- public class MyClass
- {
- /// <summary>
- /// Adds two integers and returns the result.
- /// </summary>
- /// <param name="a">The first integer to add.</param>
- /// <param name="b">The second integer to add.</param>
- /// <returns>The sum of the two integers.</returns>
- public int Add(int a, int b)
- {
- return a + b;
- }
- /// <summary>
- /// Subtracts one integer from another and returns the result.
- /// </summary>
- /// <param name="a">The integer to subtract from (the minuend).</param>
- /// <param name="b">The integer to subtract (the subtrahend).</param>
- /// <returns>The difference between the two integers.</returns>
- public int Subtract(int a, int b)
- {
- return a - b;
- }
- }
复制代码 Tests:- public class MyClassTests
- {
- [Fact]
- public void TestAdd()
- {
- // Arrange
- MyClass myClass = new MyClass();
- // Act
- int result = myClass.Add(2, 3);
- // Assert
- Assert.Equal(5, result);
- }
- [Fact]
- public void TestSubtract()
- {
- // Arrange
- MyClass myClass = new MyClass();
- // Act
- int result = myClass.Subtract(3, 2);
- // Assert
- Assert.Equal(1, result);
- }
- }
复制代码 2.使用 Codecov
2.1 注册
直接访问 https://codecov.io ,使用 GIthub 账号登录,授权后它会自动获取你账号/组织下的仓库。

2.2 设置
找到需要设置的仓库,点击 setup repo,便会出现对应的配置教程。


设置 Token
为了安全,我们不能在 yaml 直接配置我们的 token,需要在 Github 仓库的 Secrets 设置。

配置 codecov
点击第二步的链接,配置 codecov app

重新配置可以在 Installed GitHub Apps 找到

配置 workflow
添加 step:- - name: Test
- run: dotnet test /p:CollectCoverage=true /p:CoverletOutputFormat=opencover
- - name: Upload coverage reports to Codecov
- uses: codecov/codecov-action@v3
- with:
- token: ${{ secrets.CODECOV_TOKEN }}
- fail_ci_if_error: true
- paths: ./**/coverage.opencover.xml
复制代码 配置 Status check
在项目根目录添加 codecov.yml- coverage:
- # Commit status https://docs.codecov.io/docs/commit-status are used
- # to block PR based on coverage threshold.
- status:
- project:
- default:
- target: auto
- threshold: 0%
- patch:
- default:
- informational: true
复制代码 该配置要求 PR 的测试覆盖率减少Branches

通过这个设置,可以限制 main 分支不允许直接 commit,必须经过多少人 Review 才能 Merge,必须通过指定的 Actions 后才能 Merge 等等。可以用来配合覆盖率检测,提升项目的质量管控。
4.总结
在本文中,我们介绍了如何使用 Github Actions 和 Codecov 这两个工具来进行 .NET 项目的质量管控。通过在代码仓库中添加 Codecov 的 Action,我们可以自动化地收集测试覆盖率和代码质量等关键指标,并将其报告到 Codecov 的平台上,以便于团队更好地跟踪和管理项目的质量状况。
当然,Github Actions 和 Codecov 只是质量管控的一部分,要想确保项目的质量,还需要结合其他的质量控制措施,例如代码审查、单元测试、自动化测试等等。只有通过多个层面的质量控制,才能保证项目的可维护性和稳定性。
以上总结 by ChatGPT
示例:https://github.com/stulzq/DotNetActionsExample
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |