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

Azure Pipelines中能否通过变量获取DotNetCoreCLI测试的通过率与失败率?

在Azure Pipelines中获取DotNetCoreCLI测试任务的通过率与失败率

可以实现,但默认的DotNetCoreCLI@2测试任务不会自动将通过率、失败率暴露为管道变量,需要通过生成测试结果文件+解析文件提取数据+设置管道变量的流程来实现,具体步骤如下:

1. 修改测试任务,生成可解析的测试结果文件

在原DotNetCoreCLI@2任务中添加arguments参数,指定生成TRX格式的测试结果文件(这是.NET测试默认支持的结构化结果格式):

- task: DotNetCoreCLI@2
  displayName: Execute Tests
  inputs:
    command: 'test'
    projects: '**\BaseProject.dll'
    workingDirectory: '$(System.DefaultWorkingDirectory)'
    arguments: '--logger "trx;LogFileName=testResults.trx"'

执行后,测试结果文件会自动生成在$(System.DefaultWorkingDirectory)/TestResults目录下。

2. 解析测试结果文件,计算并设置管道变量

添加PowerShell(适用于Windows代理)任务,读取TRX文件的XML结构,提取总测试数、失败数,计算通过率和失败率,再通过Azure Pipelines的命令将这些值设置为全局管道变量,供后续任务调用。

- task: PowerShell@2
  displayName: Calculate Test Pass/Fail Rates
  inputs:
    targetType: 'inline'
    script: |
      # 定位测试结果文件路径
      $trxPath = Join-Path -Path $(System.DefaultWorkingDirectory) -ChildPath "TestResults/testResults.trx"
      
      # 读取并解析TRX XML文件
      $xmlContent = Get-Content -Path $trxPath -Raw
      $xml = [xml]$xmlContent
      
      # 提取测试统计数据
      $totalTests = [int]$xml.TestRun.ResultSummary.Counters.total
      $failedTests = [int]$xml.TestRun.ResultSummary.Counters.failed
      $passedTests = $totalTests - $failedTests
      
      # 计算通过率和失败率(保留2位小数,处理无测试用例的容错场景)
      $passRate = if ($totalTests -eq 0) { 0 } else { [math]::Round(($passedTests / $totalTests) * 100, 2) }
      $failRate = if ($totalTests -eq 0) { 0 } else { [math]::Round(($failedTests / $totalTests) * 100, 2) }
      
      # 设置管道变量,后续任务可通过$(PassRate)、$(FailRate)访问
      Write-Host "##vso[task.setvariable variable=PassRate;]$passRate"
      Write-Host "##vso[task.setvariable variable=FailRate;]$failRate"
      
      # 输出验证信息(可选)
      Write-Host "Total Tests: $totalTests"
      Write-Host "Passed Tests: $passedTests"
      Write-Host "Failed Tests: $failedTests"
      Write-Host "Pass Rate: $passRate%"
      Write-Host "Fail Rate: $failRate%"

3. 后续任务访问测试率变量

在之后的任意任务中,直接使用$(PassRate)和$(FailRate)即可获取对应数值,例如:

- task: PowerShell@2
  displayName: Use Test Rate Variables
  inputs:
    targetType: 'inline'
    script: |
      Write-Host "本次测试通过率:$(PassRate)%"
      Write-Host "本次测试失败率:$(FailRate)%"

注意事项

  • 如果存在多个测试项目生成多个TRX文件,需要遍历所有文件累加统计数据;
  • 若代理平台为Linux/macOS,可改用Bash脚本配合xmllint工具解析XML,逻辑与上述PowerShell脚本一致;
  • 脚本中添加了无测试用例场景的容错处理,避免出现除零错误。

内容的提问来源于stack exchange,提问作者Octávio Moreira

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 01:20:39