How do I get nunit3-console to output my debug to screen (on a Windows box)?

code_fodder picture code_fodder · Sep 25, 2017 · Viewed 7.9k times · Source

I have used NUnit to run my C# unit tests successfully within Visual Studio 2013, with the NUnit GUI and with NUnit console.

For the first two I can get to my debug output (Console.Write(...)). In Visual Studio 2013, it is viewable by clicking the "output" link after the test and in the GUI the debug is displayed in the "Output" window.

When I run this with nunit3-console.exe I just get the summary report. I tried to look at what is in the XML output (in TestResults.xml), but that just contains more of the same summary report.

How can I get my debug to also come out on the screen?

My command line looks like this:

nunit3-console.exe "c:\path\to\my\assebly.dll" --trace=Verbose --test=Regression.Tests.HelloWorld

The test HelloWorld has the line Console.Write("Hello World\r\n"); in it, and I want to see this appear on the screen (standard output).

Answer

Rob Prouse picture Rob Prouse · Sep 25, 2017

Your Console.WriteLine(...) should appear in the output, but in NUnit 3, you should use TestContext.WriteLine(...) in your tests. Because NUnit 3 is capable of running your tests in parallel, it captures that output and then prints it to the console when the test finishes running. That way, the output is matched with the test, not interleaved with other tests.

If you want your output to go out immediately when it is written, use TestContext.Progress.WriteLine(...). For example, the following test,

    [Test]
    public void ExampleOfConsoleOutput()
    {
        Console.WriteLine("Console.WriteLine In ExampleOfConsoleOutput");
        TestContext.WriteLine("TestContext.WriteLine In ExampleOfConsoleOutput");
        TestContext.Progress.WriteLine("TestContext.Progress.WriteLine In ExampleOfConsoleOutput");
    }

Outputs the following,

=> nunit.v3.TestNameInSetup.ExampleOfConsoleOutput
TestContext.Progress.WriteLine In ExampleOfConsoleOutput
Console.WriteLine In ExampleOfConsoleOutput
TestContext.WriteLine In ExampleOfConsoleOutput

Note that the Progress message was output before the other output even though it is last in the test.

You also don't need the --trace command line option. That is for NUnit internal tracing. The command line option to control output is --labels although the defaults (no command line options) show the above output.