131

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?

Julian
  • 20,008
  • 17
  • 77
  • 108

6 Answers6

118

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");
Risadinha
  • 16,058
  • 2
  • 88
  • 91
Andras Zoltan
  • 41,961
  • 13
  • 104
  • 160
  • 74
    so basically, `Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));` `Trace.WriteLine("Hello World");` – Marty Neal Feb 18 '11 at 21:08
  • 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(...) – joshgo Apr 09 '12 at 16:17
  • 7
    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... – DavidRR Feb 20 '14 at 14:44
  • 3
    `Trace.Listeners.Add(new ConsoleTraceListener());` is sufficient and then Show output from Debug in output window. – Dave Anderson Aug 21 '15 at 01:37
  • 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 Apr 18 '17 at 12:35
  • 3
    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. – Mike Walsh Jul 27 '17 at 04:19
  • @MikeWalsh yes and have you noticed how you can't select part of the text to copy it out? Absolutely crazy IMHO... – Andras Zoltan Jul 28 '17 at 11:22
  • 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](https://stackoverflow.com/a/149993/1520850) will essentially allow you to do that. Other answers on here cover this in different ways – bkwdesign Jan 31 '19 at 22:48
  • if you are using xunit checkout this link https://xunit.net/docs/capturing-output – hmota May 09 '19 at 16:48
  • 3
    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. – Alexander Høst Oct 05 '19 at 14:01
  • Should this work when I run the test as well, or only when I debug it? – FoxDeploy Sep 14 '20 at 21:37
85

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

chaliasos
  • 9,659
  • 7
  • 50
  • 87
  • 9
    requires `using System.Diagnostics;` – kmote Oct 30 '13 at 22:02
  • 7
    Don't use DateTime.Now. It's better to use Stopwatch (http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx) – suizo Jun 06 '14 at 09:06
  • 2
    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? – InteXX Jul 31 '14 at 00:14
  • 7
    @InteXX make sure you click "Debug the test", not "Run the test". it worked for me – John Henckel Jan 20 '15 at 15:35
  • @JohnHenckel: Gotcha. Thanks. Will do that. In fact Schaliasos says exactly that right in his answer; not sure how I missed it. – InteXX Jan 20 '15 at 22:26
  • There is a `Tests` output window, how do you write to this instead of `Debug`? – PeterX Feb 25 '15 at 01:16
  • You can get this to the test output if you run `dotnet test -l "console;verbosity=detailed"`. https://github.com/microsoft/vstest/issues/799#issuecomment-1003819952 – Tamás Kovács Jan 06 '23 at 01:57
16

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();
    }
}
Peter O.
  • 32,158
  • 14
  • 82
  • 96
SimplyKnownAsG
  • 904
  • 9
  • 26
6

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.

Gökhan Kurt
  • 531
  • 5
  • 13
  • 1
    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. – O. R. Mapper Apr 18 '17 at 12:40
  • Did you find any ways of seeing outputs while running tests? – hima Dec 03 '19 at 12:29
3

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");
 }
}
JJS
  • 6,431
  • 1
  • 54
  • 70
-3

Update: Load Tests functionality is deprecated.

--- original answer
You better setup a single test and create a performance test from this test. This way you can monitor the progress using the default tool set.

riezebosch
  • 1,950
  • 16
  • 29
  • "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 Apr 18 '17 at 12:39
  • https://www.visualstudio.com/en-us/docs/test/performance-testing/run-performance-tests-app-before-release#create-a-load-test – riezebosch Apr 26 '17 at 10:16