2018-8-2 更新:今天发现在 git bash 中用 dotnet test 运行 xunit 测试可以正常输出到控制台,只是在 PowerShell 与 Windows 命令行中有这个问题。
被这个问题困扰很久了,用 dotnet test 命令运行 xUnit.net 测试项目时,测试代码中的 Console.WriteLine() 输出的内容在控制台总是不显示。
之前一直以为是 xunit runner 屏蔽了控制台的输出,昨天在博问进行了提问 —— ,今天在 的源代码中苦苦搜寻, 心想只要知道是怎么屏蔽的,就有办法解除。但是,翻遍 xUnit 源代码也没找到对 Console.Out 动手脚的地方。
后来, 在博问中的回复 “启动单独的一个进程进行测试,所有输出内容都在他的进程内” 让我恍然大悟 —— xUnit 根本没有屏蔽控制台输出,只是因为 dotnet test 与 xunit runner 不在同一个进程,Console.WriteLine 在 xunit runner 进程中输出的内容,在另外一个进程中当然看不到。
罪魁祸首就是 dotnet test 所使用的 xunit runner —— xunit.runner.visualstudio ,它会在另外一个进程中运行测试,而改用 dotnet xunit 命令就可以轻松解决这个问题。
在测试项目的 .csproj 文件中添加如下的配置
dotnet xunit 运行测试成功输出"Hello World!"
PS > dotnet xunitRunning .NET Core 2.1.0 tests for framework netcoreapp2.1...xUnit.net Console Runner (64-bit .NET Core 4.6.26515.07) Discovering: XUnitConsoleOutput Discovered: XUnitConsoleOutput Starting: XUnitConsoleOutputHello World! Finished: XUnitConsoleOutput=== TEST EXECUTION SUMMARY === XUnitConsoleOutput Total: 1, Errors: 0, Failed: 0, Skipped: 0, Time: 0.194s