如何在Azure测试流水线中将TRX转HTML并添加为测试附件?
实现TRX转HTML并附加到Azure DevOps测试运行的方案
完全可以实现TRX转HTML报告,并将其作为附件添加到Azure DevOps的测试运行中。以下是具体的流水线改造步骤:
1. 修改VSTest任务,指定TRX输出路径
首先调整VSTest@3任务,明确测试结果的输出目录,方便后续工具定位TRX文件:
- task: VSTest@3 inputs: testAssemblyVer2: '**\*test*.dll' searchFolder: '$(System.DefaultWorkingDirectory)' resultsFolder: '$(Agent.TempDirectory)/TestResults' # 统一TRX输出路径 testRunTitle: 'Nightly Regression Tests' # 标记测试运行标题,后续用于匹配 publishRunAttachments: true # 确保测试运行结果被发布到Azure DevOps displayName: 'Run Nightly Regression Tests'
2. 安装TRX转HTML工具(ReportGenerator)
使用dotnet-reportgenerator-globaltool工具,它支持将TRX格式的测试结果转换为可读性强的HTML报告:
- script: dotnet tool install --global dotnet-reportgenerator-globaltool displayName: 'Install ReportGenerator'
3. 执行TRX转HTML转换
调用ReportGenerator工具,将指定目录下的TRX文件转换为HTML报告:
- script: | reportgenerator -reports:$(Agent.TempDirectory)/TestResults/*.trx -targetdir:$(Agent.TempDirectory)/TestResults/HTMLReport -reporttypes:Html displayName: 'Convert TRX to HTML Report'
可选:如果需要深色主题报告,可将-reporttypes:Html替换为-reporttypes:Html_Dark。
4. 将HTML报告附加到测试运行
通过Azure DevOps REST API,将生成的HTML报告上传为对应测试运行的附件。使用流水线内置的System.AccessToken进行身份验证:
- task: PowerShell@2 inputs: targetType: 'inline' script: | # 初始化参数 $orgUrl = "$(System.TeamFoundationCollectionUri)" $projectName = "$(System.TeamProject)" $pat = "$(System.AccessToken)" $testRunTitle = "Nightly Regression Tests" # 需与VSTest任务的标题一致 # 构建认证头 $base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$pat")) $headers = @{Authorization = "Basic $base64AuthInfo"} # 查询匹配的最新测试运行 $testRunsUrl = "$orgUrl/$projectName/_apis/test/runs?api-version=7.1-preview.3&`$filter=title eq '$testRunTitle' and completedDate ne null&`$top=1" $testRun = Invoke-RestMethod -Uri $testRunsUrl -Headers $headers -Method Get if (-not $testRun.value) { Write-Error "未找到标题为 '$testRunTitle' 的测试运行" exit 1 } $testRunId = $testRun.value[0].id # 读取HTML报告并转换为Base64 $htmlReportPath = "$(Agent.TempDirectory)/TestResults/HTMLReport/index.html" if (-not (Test-Path $htmlReportPath)) { Write-Error "HTML报告文件不存在: $htmlReportPath" exit 1 } $fileBytes = [System.IO.File]::ReadAllBytes($htmlReportPath) $base64Content = [Convert]::ToBase64String($fileBytes) # 上传附件到测试运行 $attachmentBody = @{ stream = $base64Content fileName = "Nightly_Test_Report.html" comment = "TRX转换后的HTML测试报告" attachmentType = "GeneralAttachment" } | ConvertTo-Json $uploadUrl = "$orgUrl/$projectName/_apis/test/runs/$testRunId/attachments?api-version=7.1-preview.1" Invoke-RestMethod -Uri $uploadUrl -Headers $headers -Method Post -Body $attachmentBody -ContentType "application/json" Write-Host "HTML报告已成功附加到测试运行ID: $testRunId" displayName: 'Attach HTML Report to Test Run'
关键注意事项
- 权限配置:确保流水线的服务账户拥有Azure DevOps项目的测试运行查看/编辑权限,否则API调用会失败。可在项目设置的"权限"面板中,给"构建服务(项目名)"账户分配测试管理相关权限。
- 标题一致性:VSTest任务的
testRunTitle必须与PowerShell脚本中的标题完全匹配,才能准确找到对应的测试运行。 - 备选方案:如果不需要附加到测试运行,可添加
PublishBuildArtifacts@1任务,将HTML报告发布到构建工件中,方便团队成员直接下载查看。
内容的提问来源于stack exchange,提问作者Kev
相关产品推荐
相关产品推荐

