Console.WriteLine for NET CORE 2.0 doesn't work in xUnit on Windows
Asked Answered
I

2

6

How is it recommended to write to the console in .NET CORE 2.0 C# functions which link either into a console app or a xUnit test?

I've had some luck with simply Console.WriteLine, but only with dotnet test on linux. On Windows, 'dotnet test' produces no console output except for the stats about number of tests passed vs failed.

Googling the issue, I ran upon ITestOutputHelper threads from 2015 which look out of date and or reference Visual Studio. I do not use Visual Studio because I need to stay portable to Windows + Linux. I'm using VSCode editor mostly and run most build and test commands in a terminal.

Also ITestOutputHelper is just a trivial interface:

  1. it doesn't solve any problem: sure I could rewrite all my test code to call _output.WriteLine instead of Console.WriteLine but how do I instantiate ITestOutputHelper (the official doc remains vague on the matter: https://xunit.github.io/docs/capturing-output.html)

  2. I looked into System.Diagnostics, changing all Console.WriteLine calls to Trace.TraceInformation. Unfortunately it doesn't seem .NET CORE 2.0 has implemented System.Diagnostics because my build cannot find System.Diagnostics.ConsoleTraceListener which I'd want to register as a listener by calling Trace.Listeners.Add(myConsoleTraceListener) early in the test.

So I don't need anything fancy, the unit tests do not need to run remotely, nor in parallel, running locally and sequentially is just fine, so long as I can see the output in the console. And I need to be portable to both Windows and Linux, and it looks like that's part is asking too much of XUnit. Is that really true, any ideas?

Ironwork answered 17/2, 2018 at 5:18 Comment(1)
xUnit.net has its own dotnet xunit command, github.com/xunit/xunit/issues/1407Kotz
I
3

You simply put a ITestOutputHelper in the constructor as an injection. The test framework automatically instantiates one and passes it in. You do not need to implement the interface.

public MyTestClass
{
    private readonly ITestOutputHelper _outputHelper;

    public MyTestClass(ITestOutputHelper outputHelper)
    {
        _outputHelper = outputhelper;
    }

    [Fact]
    public void MyTest()
    {
        _outputHelper.WriteLine("will go in test output");
    }
}

Make sure to reference the "xunit.runner.visualstudio" nuget package on top of the "xunit" nuget package.

Itinerancy answered 5/6, 2018 at 14:23 Comment(0)
A
1

The workaround for me was to use Console.Error.WriteLine instead of Console.WriteLine.

Aubreir answered 17/8, 2020 at 16:25 Comment(1)
Similar, I use Debug.WriteLine and look at the "DEBUG CONSOLE" in VS Code (using C# Dev Kit extension on macOS)Loveland

© 2022 - 2024 — McMap. All rights reserved.