How to write to Console.Out during execution of an MSTest test

133,359

Solution 1

The Console output is not appearing is because the backend code is not running in the context of the test.

You're probably better off using Trace.WriteLine (In System.Diagnostics) and then adding a trace listener which writes to a file.

This topic from MSDN shows a way of doing this.


According to Marty Neal's and Dave Anderson's comments:

using System;
using System.Diagnostics;

...

Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));
// or Trace.Listeners.Add(new ConsoleTraceListener());
Trace.WriteLine("Hello World");

Solution 2

Use the Debug.WriteLine. This will display your message in the Output window immediately. The only restriction is that you must run your test in Debug mode.

[TestMethod]
public void TestMethod1()
{
    Debug.WriteLine("Time {0}", DateTime.Now);
    System.Threading.Thread.Sleep(30000);
    Debug.WriteLine("Time {0}", DateTime.Now);
}

Output

enter image description here

Solution 3

I found a solution of my own. I know that Andras answer is probably the most consistent with MSTEST, but I didn't feel like refactoring my code.

[TestMethod]
public void OneIsOne()
{
    using (ConsoleRedirector cr = new ConsoleRedirector())
    {
        Assert.IsFalse(cr.ToString().Contains("New text"));
        /* call some method that writes "New text" to stdout */
        Assert.IsTrue(cr.ToString().Contains("New text"));
    }
}

The disposable ConsoleRedirector is defined as:

internal class ConsoleRedirector : IDisposable
{
    private StringWriter _consoleOutput = new StringWriter();
    private TextWriter _originalConsoleOutput;
    public ConsoleRedirector()
    {
        this._originalConsoleOutput = Console.Out;
        Console.SetOut(_consoleOutput);
    }
    public void Dispose()
    {
        Console.SetOut(_originalConsoleOutput);
        Console.Write(this.ToString());
        this._consoleOutput.Dispose();
    }
    public override string ToString()
    {
        return this._consoleOutput.ToString();
    }
}

Solution 4

I had the same issue and I was "Running" the tests. If I instead "Debug" the tests the Debug output shows just fine like all others Trace and Console. I don't know though how to see the output if you "Run" the tests.

Solution 5

It's not the console, but it is in the output panel.

public class Test
{
 public TestContext TestContext { get; set; }

 [TestMethod]
 public void Foo()
 {
   TestContext.WriteLine("Hello World");
 }
}
Share:
133,359
Julian
Author by

Julian

Software Craftsman

Updated on January 29, 2022

Comments

  • Julian
    Julian over 2 years

    Context:
    We have some users reporting issues with a file upload feature in our web application. It only happens occasionally and without any special pattern. We have been trying to figure it out for a long time, adding debug information anywhere we can think it might help, crawling the logs etc, but we have not been able to reproduce or figure it out.

    Problem:
    I'm now trying to reproduce this by using MSTest and WatiN to repeat the operation that is supposed to fail a large number of times (several hundreds). Just to have a clue about how far in the loop the test has gotten, I want to print something like:

    Console.WriteLine(String.Format("Uploaded file, attempt {0} of {1}", i, maxUploads));
    

    This does however not appear in the Output window. Now I know that you'll get the console output in the test results (as well as what you output from Debug.Writeline etc), but this is not available until after the test has finished. And since my test with hundreds of repetitions could take quite some time, I'd like to know how far it has gotten.

    Question:
    Is there a way I can get the console output in the Output window during test execution?

  • Marty Neal
    Marty Neal over 13 years
    so basically, Trace.Listeners.Add(new TextWriterTraceListener(Console.Out)); Trace.WriteLine("Hello World");
  • joshgo
    joshgo about 12 years
    Nice, I like it. To get around this I've used log4net with a filelogger. You'll have to change your calls from Console.WriteLine to Logger.Info(...)
  • kmote
    kmote over 10 years
    requires using System.Diagnostics;
  • DavidRR
    DavidRR over 10 years
    Hmmm, I'm finding that the suggestion by @Martin Neal sends both Trace.WriteLine() and Console.WriteLine() output to the Test Results View, not the Output View. (And note that in the Test Results View, it may be necessary to add the Output (Stdout) column by right-clicking and selecting Add/Remove Columns....) But, perhaps I'm still not seeing output in the Output View means that I'm missing something...
  • suizo
    suizo about 10 years
    Don't use DateTime.Now. It's better to use Stopwatch (msdn.microsoft.com/en-us/library/…)
  • InteXX
    InteXX almost 10 years
    I couldn't get this to work. When I run the test the Output Window immediately switches to Build and nothing is sent to Debug. Your thoughts?
  • John Henckel
    John Henckel over 9 years
    @InteXX make sure you click "Debug the test", not "Run the test". it worked for me
  • InteXX
    InteXX over 9 years
    @JohnHenckel: Gotcha. Thanks. Will do that. In fact Schaliasos says exactly that right in his answer; not sure how I missed it.
  • PeterX
    PeterX over 9 years
    There is a Tests output window, how do you write to this instead of Debug?
  • Dave Anderson
    Dave Anderson almost 9 years
    Trace.Listeners.Add(new ConsoleTraceListener()); is sufficient and then Show output from Debug in output window.
  • O. R. Mapper
    O. R. Mapper about 7 years
    This doesn't seem to work. The information I send to Trace.WriteLine appears only in the test output window, as @DavidRR says.
  • O. R. Mapper
    O. R. Mapper about 7 years
    "This way you can monitor the progress using the default tool set." - how? The problem I'm seeing is exactly that once a test runs, it is a black box and I only get to see the output (that I am gradually writing while the test is running) after the test has finished running, in the Output window.
  • O. R. Mapper
    O. R. Mapper about 7 years
    I can get something to show using System.Diagnostics.Debug.WriteLine while debugging tests, but how do you get Console.WriteLine to work? This doesn't end up in the normal (live updated) output for me.
  • Anish
    Anish about 7 years
  • Mike Walsh
    Mike Walsh almost 7 years
    I was struggling to actually find the output in VS2017... TestExplorer window -> Click on an individual test -> If the test had ouput, in the detail window under the elapsed time there is the word "ouput" which is a link to a new window.
  • Andras Zoltan
    Andras Zoltan almost 7 years
    @MikeWalsh yes and have you noticed how you can't select part of the text to copy it out? Absolutely crazy IMHO...
  • bkwdesign
    bkwdesign over 5 years
    Basically, you're wanting to make assertions about things that are normally logged out to the console. Using this answer, and combining it with a memory stream will essentially allow you to do that. Other answers on here cover this in different ways
  • hmota
    hmota about 5 years
    if you are using xunit checkout this link xunit.net/docs/capturing-output
  • Alexander Høst
    Alexander Høst over 4 years
    If you're using Xunit, just take ITestOutputHelper in through the ctor and call WriteLine on it. Took a while before I found out how to write during integration testing, hope this helps someone.
  • hima
    hima over 4 years
    Did you find any ways of seeing outputs while running tests?
  • FoxDeploy
    FoxDeploy almost 4 years
    Should this work when I run the test as well, or only when I debug it?