You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Problem Matcher将xUnit/dotnet测试输出转为GitHub Actions注解?

用GitHub Problem Matcher解析dotnet test输出生成PR注解的问题

现有GitHub Action配置

我目前用以下GitHub Action运行.NET xUnit测试:

jobs:
  build-net:
    name: .NET build & test
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v3
    - name: Setup .NET
      uses: actions/setup-dotnet@v3
      with:
        dotnet-version: 7.0.100      
    - name: Restore dependencies
      run: dotnet restore
    - name: Build
      run: dotnet build --no-restore
    - name: Test
      run: dotnet test --no-build

dotnet test输出示例

测试失败时,每个失败测试会输出类似内容:

Failed Library.Tests.UnitTest1.DeliberateFail2 [< 1 ms]
  Error Message:
   System.Exception : Error message
  Stack Trace:
     at Library.Tests.UnitTest1.DeliberateFail2() in /home/runner/work/Library/Library.Tests/UnitTest1.cs:line 30
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Void** arguments, Signature sig, Boolean isConstructor)
   at System.Reflection.MethodInvoker.Invoke(Object obj, IntPtr* args, BindingFlags invokeAttr)

最后会输出汇总信息:

Failed!  - Failed:     2, Passed:   133, Skipped:     0, Total:   135, Duration: 639 ms - Library.Tests.dll (net7.0)
Error: Process completed with exit code 1.

问题与需求

当前Action只会显示测试步骤失败的提示,但dotnet build的警告能直接在PR中生成指向代码行的注解,dotnet test却只返回退出码1的提示。我需要为每个失败测试生成代码注解,但不想采用以下方案:

  • 引入新依赖或输出处理器
  • 使用第三方Action发布测试结果或解析trx文件

根据GitHub文档,应该可以通过Problem Matcher解决——这是一种用正则表达式将命令行输出转换为GitHub注解的机制,类似VSCode的问题匹配。

尝试过的配置及问题

我尝试编写正则表达式解析dotnet test输出,保存为.github/xunit.json:

单正则配置

{
  "problemMatcher": [
    {
      "owner": "xunit",
      "pattern": [ 
        {
          "regexp": "^\\s*Failed\\s(.*)([\\s\\S]*?)(Stack\\sTrace:\\s*at\\s)(.*)\\s+in\\s+(.*):line\\s+(\\d+)\\s*$",
          "file": 5,
          "fromPath": 5,
          "line": 6,
          "message": 2
        }
      ]
    }
  ]
}

然后在Action中引入:

- name: Build
      run: dotnet build --no-restore
    - name: set matcher
      run: echo "::add-matcher::${{ github.workspace }}/.github/xunit.json"
    - name: Test
      run: dotnet test --no-build --logger "trx;LogFileName=test-results.trx"

但没有生效,未生成任何注解。

多行匹配配置

我还尝试了多行问题匹配:

{
  "problemMatcher": [
    {
      "owner": "xunit",
      "pattern": [ 
        {
          "regexp": "^\\s*Failed\\s(.*)$",
          "message": 1
        },
        {
          "regexp": "^\\s*at\\s(.*)\\s+in\\s+(.*):line\\s+(\\d+)\\s*$",
          "file": 2,
          "fromPath": 2,
          "line": 3
        }
      ]
    }
  ]
}

同样没有效果。

我没找到现成的针对dotnet test的GitHub Problem Matcher,希望有人能帮忙修正正则表达式,或者指出Action配置中的错误。

内容的提问来源于stack exchange,提问作者Keith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 00:20:31