[c#] Can I write into the console in a unit test? If yes, why doesn't the console window open?

I have a test project in Visual Studio. I use Microsoft.VisualStudio.TestTools.UnitTesting.

I add this line in one of my unit tests:

Console.WriteLine("Some foo was very angry with boo");
Console.ReadLine();

When I run the test, the test passes, but the console window is not opened at all.

Is there a way to make the console window available to be interacted via a unit test?

This question is related to c# .net visual-studio unit-testing console-application

The answer is


IMHO, output messages are relevant only for failed test cases in most cases. I made up the below format, and you can make your own too. This is displayed in the Visual Studio Test Explorer Window itself.

How can we throw this message in the Visual Studio Test Explorer Window?

Sample code like this should work:

if(test_condition_fails)
    Assert.Fail(@"Test Type: Positive/Negative.
                Mock Properties: someclass.propertyOne: True
                someclass.propertyTwo: True
                Test Properties: someclass.testPropertyOne: True
                someclass.testPropertyOne: False
                Reason for Failure: The Mail was not sent on Success Task completion.");

You can have a separate class dedicated to this for you.


There are several ways to write output from a Visual Studio unit test in C#:

  • Console.Write - The Visual Studio test harness will capture this and show it when you select the test in the Test Explorer and click the Output link. Does not show up in the Visual Studio Output Window when either running or debugging a unit test (arguably this is a bug).
  • Debug.Write - The Visual Studio test harness will capture this and show it in the test output. Does appear in the Visual Studio Output Window when debugging a unit test, unless Visual Studio Debugging options are configured to redirect Output to the Immediate Window. Nothing will appear in the Output (or Immediate) Window if you simply run the test without debugging. By default only available in a Debug build (that is, when DEBUG constant is defined).
  • Trace.Write - The Visual Studio test harness will capture this and show it in the test output. Does appear in the Visual Studio Output (or Immediate) Window when debugging a unit test (but not when simply running the test without debugging). By default available in both Debug and Release builds (that is, when TRACE constant is defined).

Confirmed in Visual Studio 2013 Professional.


I have an easier solution (that I used myself recently, for a host of lazy reasons). Add this method to the class you are working in:

public static void DumbDebug(string message)
{
    File.WriteAllText(@"C:\AdHocConsole\" + message + ".txt", "this is really dumb. I wish Microsoft had more obvious solutions to its solutions problems.");
}

Then...open up the directory AdHocConsole, and order by created time. Make sure when you add your 'print statements'. They are distinct though, else there will be juggling.


Visual Studio For Mac

None of the other solutions worked on Visual Studio for Mac

If you are using NUnit, you can add a small .NET Console Project to your solution, and then reference the project you wish to test in the References of that new Console Project.

Whatever you were doing in your [Test()] methods can be done in the Main of the console application in this fashion:

class MainClass
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Console");

        // Reproduce the unit test
        var classToTest = new ClassToTest();
        var expected = 42;
        var actual = classToTest.MeaningOfLife();
        Console.WriteLine($"Pass: {expected.Equals(actual)}, expected={expected}, actual={actual}");
    }
}

You are free to use Console.Write and Console.WriteLine in your code under these circumstances.


In Visual Studio 2017, "TestContext" doesn't show the Output link into Test Explorer.

However, Trace.Writeline() shows the Output link.


Someone commented about this apparently new functionality in Visual Studio 2013. I wasn't sure what he meant at first, but now that I do, I think it deserves its own answer.

We can use Console.WriteLine normally and the output is displayed, just not in the Output window, but in a new window after we click "Output" in the test details.

Enter image description here


You could use this line to write to Output Window of the Visual Studio:

System.Diagnostics.Debug.WriteLine("Matrix has you...");

Must run in Debug mode.


Debug.WriteLine() can be used as well.


As stated, unit tests are designed to run without interaction.

However, you can debug unit tests, just like any other code. The easiest way is to use the Debug button in the Test Results tab.

Being able to debug means being able to use breakpoints. Being able to use breakpoints, then, means being able to use Tracepoints, which I find extremely useful in every day debugging.

Essentially, Tracepoints allow you to write to the Output window (or, more accurately, to standard output). Optionally, you can continue to run, or you can stop like a regular breakpoint. This gives you the "functionality" you are asking for, without the need to rebuild your code, or fill it up with debug information.

Simply add a breakpoint, and then right-click on that breakpoint. Select the "When Hit..." option:

When hitting option

Which brings up the dialog:

When a breakpoint is hit

A few things to note:

  1. Notice that the breakpoint is now shown as a diamond, instead of a sphere, indicating a trace point
  2. You can output the value of a variable by enclosing it like {this}.
  3. Uncheck the "Continue Execution" checkbox to have the code break on this line, like any regular breakpoint
  4. You have the option of running a macro. Please be careful - you may cause harmful side effects.

See the documentation for more details.


You can use

Trace.WriteLine()

to write to the Output window when debugging a unit test.


First of all unit tests are, by design, supposed to run completely without interaction.

With that aside, I don't think there's a possibility that was thought of.

You could try hacking with the AllocConsole P/Invoke which will open a console even when your current application is a GUI application. The Console class will then post to the now opened console.


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 .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

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 console-application

How to run .NET Core console app from the command line ASP.NET Core configuration for .NET Core console application How to keep console window open How to navigate a few folders up? How to stop C# console applications from closing automatically? Could not load file or assembly ... An attempt was made to load a program with an incorrect format (System.BadImageFormatException) Can I write into the console in a unit test? If yes, why doesn't the console window open? What is the command to exit a Console application in C#? Can't specify the 'async' modifier on the 'Main' method of a console app Why is the console window closing immediately once displayed my output?