如何实现.NET测试仅重跑失败用例?(C#、Azure Pipelines、BrowserStack)
需求完全可行,以下是具体实现思路和步骤
核心思路
通过测试框架生成失败用例清单 + Azure Pipelines条件触发重跑任务 + 指定仅运行失败用例的组合方式,实现只重跑初次失败的测试用例,无需重复执行整个测试任务。
具体实现步骤
1. 利用测试框架生成失败测试报告
C#常用的xUnit、NUnit都支持生成结构化测试报告(如XML格式),方便后续提取失败用例:
- xUnit:运行测试时添加参数
--logger "xunit;LogFilePath=test-results.xml",生成包含测试结果的XML报告。 - NUnit:使用
--result test-results.xml参数生成报告。
2. 提取失败用例清单
在初始测试任务结束后,通过脚本(PowerShell或C#工具)解析测试报告,提取失败用例的全限定名(类名.方法名),保存到文件(如failed-tests.txt):
示例PowerShell脚本:
$xml = [xml](Get-Content test-results.xml) $failedTests = $xml.SelectNodes("//test-case[@result='Failed']") | ForEach-Object { $_.classname + "." + $_.name } $failedTests | Out-File -FilePath failed-tests.txt -Encoding utf8
这个步骤仅在初始测试失败时执行,通过Azure Pipelines的condition: failed()控制。
3. 触发失败用例重跑任务
在Pipeline中添加依赖于初始测试任务的重跑任务,仅当初始测试失败时触发(通过condition: failed('RunInitialTests')):
- 先下载之前保存的
failed-tests.txt文件; - 将失败用例拼接成测试过滤条件(如用
|分隔多个用例); - 运行测试时通过
dotnet test的--filter参数指定仅运行这些失败用例:dotnet test --filter "FullyQualifiedName~(TestClass1.TestMethod1|TestClass2.TestMethod2)"
4. 适配BrowserStack的注意事项
- 确保重跑任务的BrowserStack配置(设备型号、浏览器版本、环境变量等)与初始测试完全一致,避免环境差异导致的无效重跑;
- 重跑的测试会话会在BrowserStack仪表板中单独记录,可直接查看失败用例的重跑结果。
简化Pipeline示例(YAML)
jobs: - job: RunInitialTests displayName: 执行初始测试 steps: - task: DotNetCoreCLI@2 displayName: 运行全部测试 inputs: command: test projects: '**/*Tests.csproj' arguments: '--logger "xunit;LogFilePath=test-results.xml"' continueOnError: true # 允许任务失败后继续执行后续步骤 - task: PowerShell@2 displayName: 提取失败测试用例 inputs: targetType: 'inline' script: | $xml = [xml](Get-Content test-results.xml) $failedTests = $xml.SelectNodes("//test-case[@result='Failed']") | ForEach-Object { $_.classname + "." + $_.name } $failedTests | Out-File -FilePath failed-tests.txt -Encoding utf8 condition: failed() - task: PublishPipelineArtifact@1 displayName: 上传失败测试清单 inputs: targetPath: 'failed-tests.txt' artifact: 'failed-tests' condition: failed() - job: RetryFailedTests displayName: 重跑失败测试用例 dependsOn: RunInitialTests condition: failed('RunInitialTests') steps: - task: DownloadPipelineArtifact@2 displayName: 下载失败测试清单 inputs: source: current artifact: 'failed-tests' path: $(System.DefaultWorkingDirectory) - task: PowerShell@2 displayName: 生成测试过滤规则 inputs: targetType: 'inline' script: | $failedTests = Get-Content failed-tests.txt $filter = $failedTests -join "|" Write-Host "##vso[task.setvariable variable=TestFilter]$filter" - task: DotNetCoreCLI@2 displayName: 执行失败用例重跑 inputs: command: test projects: '**/*Tests.csproj' arguments: '--filter "FullyQualifiedName~($(TestFilter))" --logger "xunit;LogFilePath=retry-test-results.xml"'
内容的提问来源于stack exchange,提问作者HANSTKE
相关产品推荐
相关产品推荐

