如何通过dotnet test/NUnit控制台运行器打印测试用例及成败状态?
实现自定义测试用例状态输出格式的方法
以下几种方案可以满足你对测试用例名称+状态(带自定义前缀)的输出需求:
方案1:NUnit控制台+脚本解析结果XML
NUnit控制台可以生成包含完整测试信息的XML报告,再通过脚本解析提取并格式化输出:
- 首先生成测试结果XML:
nunit3-console.exe YourTestAssembly.dll --result=TestResults.xml;format=nunit3
- 用PowerShell脚本解析并输出目标格式(支持提取自定义分类作为前缀):
[xml]$testResults = Get-Content TestResults.xml foreach ($test in $testResults.testRun.testSuite.testCase) { $status = $test.result # 从测试分类中提取前缀(对应你示例里的Detailed、Construct) $prefixNode = $test.properties.property | Where-Object { $_.name -eq "Category" } $prefix = if ($prefixNode) { "$($prefixNode.'#text') " } else { "" } Write-Host "$($test.name) -->$prefix$status" }
方案2:dotnet test 结合命令行过滤
通过dotnet test的详细日志输出,配合命令行工具过滤配对测试名称和状态:
Linux/macOS 下使用grep+paste:
dotnet test --logger "console;verbosity=detailed" 2>&1 | grep -E "(Test Name:|Outcome:)" | paste - - | sed 's/Test Name: //; s/Outcome: / --> /'
Windows 下使用PowerShell处理:
$testOutput = dotnet test --logger "console;verbosity=detailed" 2>&1 | Select-String -Pattern "Test Name:|Outcome:" for ($i=0; $i -lt $testOutput.Count; $i+=2) { $testName = $testOutput[$i].Line -replace "Test Name: ", "" $status = $testOutput[$i+1].Line -replace "Outcome: ", "" Write-Host "$testName -->$status" }
方案3:编写NUnit自定义测试监听器
如果需要更灵活的定制(比如直接在测试运行时输出),可以实现NUnit的测试监听器:
- 创建类库项目,引用
NUnit.EngineNuGet包,编写监听器代码:
using NUnit.Engine; using System.Xml; public class CustomTestOutputListener : ITestListener { public void OnTestEvent(string report) { var doc = new XmlDocument(); doc.LoadXml(report); var testCaseNode = doc.SelectSingleNode("//test-case"); if (testCaseNode == null) return; var testName = testCaseNode.Attributes["fullname"]?.Value; var status = testCaseNode.Attributes["result"]?.Value; // 提取自定义分类作为前缀 var categoryNode = testCaseNode.SelectSingleNode("//property[@name='Category']"); var prefix = categoryNode != null ? $"{categoryNode.InnerText} " : ""; Console.WriteLine($"{testName} -->{prefix}{status}"); } }
- 编译后,在NUnit控制台运行时指定监听器:
nunit3-console.exe YourTestAssembly.dll --test-listener=YourCustomListener.dll
内容的提问来源于stack exchange,提问作者user19540656
相关产品推荐
相关产品推荐

