.net-core - NET CORE 2.0 的 Console.WriteLine 在 Windows 上的 xUnit 中不起作用

标签 .net-core xunit

建议如何在链接到控制台应用程序或 xUnit 测试的 .NET CORE 2.0 C# 函数中写入控制台?

我对简单的 Console.WriteLine 有一些运气,但仅限于 dotnet test在 Linux 上。在 Windows 上,“dotnet test”不会产生控制台输出,除了有关通过与失败的测试数量的统计信息。

谷歌搜索这个问题,我从 2015 年开始运行 ITestOutputHelper 线程,这些线程看起来已经过时或引用了 Visual Studio。我不使用 Visual Studio,因为我需要保持可移植到 Windows + Linux。我主要使用 VSCode 编辑器并在终端中运行大多数构建和测试命令。

此外 ITestOutputHelper 只是一个简单的接口(interface):

  • 它没有解决任何问题:当然我可以重写我所有的测试代码来调用 _output.WriteLine 而不是 Console.WriteLine 但是我如何实例化 ITestOutputHelper (官方文档对此事仍然含糊不清:https://xunit.github.io/docs/capturing-output.html)
  • 我查看了 System.Diagnostics,将所有 Console.WriteLine 调用更改为 Trace.TraceInformation。不幸的是,.NET CORE 2.0 似乎没有实现 System.Diagnostics,因为我的构建找不到 System.Diagnostics.ConsoleTraceListener,我想通过在测试早期调用 Trace.Listeners.Add(myConsoleTraceListener) 将其注册为监听器。

  • 所以我不需要任何花哨的东西,单元测试不需要远程运行,也不需要并行运行,本地顺序运行就可以了,只要我能在控制台中看到输出即可。而且我需要同时移植到 Windows 和 Linux,看起来这部分是对 XUnit 的要求太多了。这是真的吗,有什么想法吗?

    最佳答案

    您只需在构造函数中放置一个 ITestOutputHelper 作为注入(inject)。测试框架会自动实例化一个并传入。你不需要实现接口(interface)。

    public MyTestClass
    {
        private readonly ITestOutputHelper _outputHelper;
    
        public MyTestClass(ITestOutputHelper outputHelper)
        {
            _outputHelper = outputhelper;
        }
    
        [Fact]
        public void MyTest()
        {
            _outputHelper.WriteLine("will go in test output");
        }
    }
    

    确保引用顶部的“xunit.runner.visualstudio”nuget 包
    “xunit”nuget 包。

    关于.net-core - NET CORE 2.0 的 Console.WriteLine 在 Windows 上的 xUnit 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48838133/

    相关文章:

    c# - 如何对使用 Response.OnStarting 的 .NET 中间件进行单元测试

    c# - 如何使用 XUnit 对 Web API Controller 进行单元测试

    c# - 在 Entity Framework Core 中创建迁移时如何配置 DbContext?

    c# - 如何使用 Moq 为异步函数抛出异常

    visual-studio - 在 .NET Core 2.0 中查看项目属性时出错

    c# - xUnit 断言两个值在一定公差范围内相等

    c# - 尝试使用 HttpClient 检索访问 token 时出现错误

    c# - 在ConfigureServices中使用DI?

    c# - 如何使用TokenSource取消测试方法?

    c# - 创建一个 TestServer 并使用 XUnit 和 ASP.NET Core 1.0 的依赖注入(inject)