翼度科技»论坛 编程开发 .net 查看内容

.NET Github Actions 测试覆盖率

3

主题

3

帖子

9

积分

新手上路

Rank: 1

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

1.测试

创建一个 xUnit 单元测试项目。
Class
  1. /// /// Represents a class with methods to perform addition and subtraction operations./// public class MyClass{    ///     /// Adds two integers and returns the result.    ///     /// The first integer to add.    /// The second integer to add.    /// The sum of the two integers.    public int Add(int a, int b)    {        return a + b;    }    ///     /// Subtracts one integer from another and returns the result.    ///     /// The integer to subtract from (the minuend).    /// The integer to subtract (the subtrahend).    /// The difference between the two integers.    public int Subtract(int a, int b)    {        return a - b;    }}
复制代码
Tests:
  1. 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:
  1. - 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
  1. 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

来源:https://www.cnblogs.com/stulzq/archive/2023/03/08/17196222.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

举报 回复 使用道具