[c#] How can I write output from a unit test?

Any call in my unit tests to either Debug.Write(line) or Console.Write(Line) simply gets skipped over while debugging and the output is never printed. Calls to these functions from within classes I'm using work fine.

I understand that unit testing is meant to be automated, but I still would like to be able to output messages from a unit test.

This question is related to c# visual-studio unit-testing debugging mstest

The answer is


Console.WriteLine won't work. Only Debug.WriteLine() or Trace.WriteLine() will work, in debug mode.

I do the following: include using System.Diagnostics in the test module. Then, use Debug.WriteLine for my output, right click on the test, choose Debug Selected Tests. The result output will now appear in the Output window below. I use Visual Studio 2017 vs 15.8.1, with the default unit test framework VS provides.


Trace.WriteLine should work provided you select the correct output (the dropdown labeled with "Show output from" found in the Output window).


If you're running tests with dotnet test, you may find that Console.Error.WriteLine produces output. This is how I've worked around the issue with NUnit tests, which also seem to have all Debug, Trace and stdout output suppressed.


It depends on your test runner... for instance, I'm using xUnit, so in case that's what you are using, follow these instructions:

https://xunit.github.io/docs/capturing-output.html

This method groups your output with each specific unit test.

using Xunit;
using Xunit.Abstractions;

public class MyTestClass
{
    private readonly ITestOutputHelper output;

    public MyTestClass(ITestOutputHelper output)
    {
        this.output = output;
    }

    [Fact]
    public void MyTest()
    {
        var temp = "my class!";
        output.WriteLine("This is output from {0}", temp);
    }
}

There's another method listed in the link I provided for writing to your Output window, but I prefer the previous.


I've accidentally found that DebugView (with enabled Capture > Capture Win32 option) will capture writes to System.Console.

Example test:

[Test]
public void FooTest()
{
    for (int i = 0; i < 5; i++)
        Console.WriteLine($"[{DateTime.UtcNow.ToString("G")}] Hello World");
}

enter image description here


I think it is still actual.

You can use this NuGet package: Bitoxygen.Testing.Pane

Call the custom WriteLine method from this library. It creates a Testing pane inside the Output window and puts messages there always (during each test, it runs independently of DEBUG and TRACE flags).

To make tracing more easy I can recommend to create a base class:

[TestClass]
public abstract class BaseTest
{
    #region Properties
    public TestContext TestContext { get; set; }

    public string Class
    {
        get { return this.TestContext.FullyQualifiedTestClassName; }
    }
    public string Method
    {
        get { return this.TestContext.TestName; }
    }
    #endregion

    #region Methods
    protected virtual void Trace(string message)
    {
        System.Diagnostics.Trace.WriteLine(message);

        Output.Testing.Trace.WriteLine(message);
    }
    #endregion
}

[TestClass]
public class SomeTest : BaseTest
{
    [TestMethod]
    public void SomeTest1()
    {
        this.Trace(string.Format("Yeah: {0} and {1}", this.Class, this.Method));
    }
}

A different variant of the cause/solution:

My issue was that I was not getting an output because I was writing the result set from an asynchronous LINQ call to the console in a loop in an asynchronous context:

var p = _context.Payment.Where(pp => pp.applicationNumber.Trim() == "12345");

p.ForEachAsync(payment => Console.WriteLine(payment.Amount));

And so the test was not writing to the console before the console object was cleaned up by the runtime (when running only one test).

The solution was to convert the result set to a list first, so I could use the non-asynchronous version of forEach():

var p = _context.Payment.Where(pp => pp.applicationNumber.Trim() == "12345").ToList();

p.ForEachAsync(payment =>Console.WriteLine(payment.Amount));

It is indeed depending on the test runner as @jonzim mentioned. For NUnit 3 I had to use NUnit.Framework.TestContext.Progress.WriteLine() to get running output in the Output window of Visual Studio 2017.

NUnit describes how to: here

To my understanding this revolves around the added parallelization of test execution the test runners have received.


In Visual Studio 2017, you can see the output from test explorer.

1) In your test method, Console.WriteLine("something");

2) Run the test.

3) In Test Explorer window, click the Passed Test Method.

4) And click the "Output" link.

enter image description here

And click "Output", you can see the result of Console.Writeline(). enter image description here


Solved with the following example:

public void CheckConsoleOutput()
{
    Console.WriteLine("Hello, World!");
    Trace.WriteLine("Trace Trace the World");
    Debug.WriteLine("Debug Debug World");
    Assert.IsTrue(true);
}

After running this test, under 'Test Passed', there is the option to view the output, which will bring up the output window.


I'm using xUnit so this is what I use:

Debugger.Log(0, "1", input);

PS: you can use Debugger.Break(); too, so you can see your log in out.


I was also trying to get Debug or Trace or Console or TestContext to work in unit testing.

None of these methods would appear to work or show output in the output window:

    Trace.WriteLine("test trace");
    Debug.WriteLine("test debug");
    TestContext.WriteLine("test context");
    Console.WriteLine("test console");

Visual Studio 2012 and greater

(from comments) In Visual Studio 2012, there is no icon. Instead, there is a link in the test results called Output. If you click on the link, you see all of the WriteLine.

Prior to Visual Studio 2012

I then noticed in my Test Results window, after running the test, next to the little success green circle, there is another icon. I doubled clicked it. It was my test results, and it included all of the types of writelines above.


I get no output when my Test/Test Settings/Default Processor Architecture setting and the assemblies that my test project references are not the same. Otherwise Trace.Writeline() works fine.


Try using:

Console.WriteLine()

The call to Debug.WriteLine will only be made during when DEBUG is defined.

Other suggestions are to use: Trace.WriteLine as well, but I haven't tried this.

There is also an option (not sure if Visual Studio 2008 has it), but you can still Use Debug.WriteLine when you run the test with Test With Debuggeroption in the IDE.


In VS 2019

  1. in the main VS menu bar click: View -> Test Explorer
  2. Right-click your test method in Test Explorer -> Debug
  3. Click the additional output link as seen in the screenshot below.

enter image description here

You can use:

  • Debug.WriteLine
  • Console.WriteLine
  • TestContext.WriteLine

all will log to the additional output window.


Are you sure you're running your unit tests in Debug? Debug.WriteLine won't be called in Release builds.

Two options to try are:

  • Trace.WriteLine(), which is built into release builds as well as debug

  • Undefine DEBUG in your build settings for the unit test


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to visual-studio

VS 2017 Git Local Commit DB.lock error on every commit How to remove an unpushed outgoing commit in Visual Studio? How to download Visual Studio Community Edition 2015 (not 2017) Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio Code pylint: Unable to import 'protorpc' Open the terminal in visual studio? Is Visual Studio Community a 30 day trial? How can I run NUnit tests in Visual Studio 2017? Visual Studio 2017: Display method references

Examples related to unit-testing

Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0 How to test the type of a thrown exception in Jest Unit Tests not discovered in Visual Studio 2017 Class Not Found: Empty Test Suite in IntelliJ Angular 2 Unit Tests: Cannot find name 'describe' Enzyme - How to access and set <input> value? Mocking HttpClient in unit tests Example of Mockito's argumentCaptor How to write unit testing for Angular / TypeScript for private methods with Jasmine Why is the Visual Studio 2015/2017/2019 Test Runner not discovering my xUnit v2 tests

Examples related to debugging

How do I enable logging for Spring Security? How to run or debug php on Visual Studio Code (VSCode) How do you debug React Native? How do I debug "Error: spawn ENOENT" on node.js? How can I inspect the file system of a failed `docker build`? Swift: print() vs println() vs NSLog() JavaScript console.log causes error: "Synchronous XMLHttpRequest on the main thread is deprecated..." How to debug Spring Boot application with Eclipse? Unfortunately MyApp has stopped. How can I solve this? 500 internal server error, how to debug

Examples related to mstest

Entity Framework Provider type could not be loaded? Unit testing private methods in C# How can we run a test method with multiple parameters in MSTest? How to write to Console.Out during execution of an MSTest test How can I write output from a unit test? Unit Testing: DateTime.Now How do I use Assert to verify that an exception has been thrown? NUnit vs. MbUnit vs. MSTest vs. xUnit.net