How to Write to Console.Out During Execution of an Mstest Test

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

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");

How to Console.WriteLine from [TestMethod]?

you should replace Console.WriteLine with System.Diagnostics.Debug.WriteLine(...)

and you will see the output in the Visual Studio Debug Output Window.

Edit: just found out now this is a duplicated question, look here:

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

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

NOTE: The original answer below should work for any version of Visual Studio up through Visual Studio 2012. Visual Studio 2013 does not appear to have a Test Results window any more. Instead, if you need test-specific output you can use @Stretch's suggestion of Trace.Write() to write output to the Output window.


The Console.Write method does not write to the "console" -- it writes to whatever is hooked up to the standard output handle for the running process. Similarly, Console.Read reads input from whatever is hooked up to the standard input.

When you run a unit test through Visual Studio 2010, standard output is redirected by the test harness and stored as part of the test output. You can see this by right-clicking the Test Results window and adding the column named "Output (StdOut)" to the display. This will show anything that was written to standard output.

You could manually open a console window, using P/Invoke as sinni800 says. From reading the AllocConsole documentation, it appears that the function will reset stdin and stdout handles to point to the new console window. (I'm not 100% sure about that; it seems kind of wrong to me if I've already redirected stdout for Windows to steal it from me, but I haven't tried.)

In general, though, I think it's a bad idea; if all you want to use the console for is to dump more information about your unit test, the output is there for you. Keep using Console.WriteLine the way you are, and check the output results in the Test Results window when it's done.

How to write MS Unit Test for the code having console.writeline

If you really want to test the Concole.WriteLine calls I would create a class with an interface to encapsulate the Console.WriteLine. Could look like this.

public class ConsoleService : IConsoleService
{
public void WriteToConsole(string text)
{
Console.WriteLine(text);
}
}

Then you can use this service in your PrintData method and mock the calls in your test and verify the calls; for example with Moq.

Easier would be to return a List from PrintData and add each entry to the list instead of Console.WriteLine(input[i]); because then you can test if the correct values where added. And in your application you simply can print all entries with a for each loop.

So you have to change your code to make it testable. But your code would be cleaner after this (I would hardly recommend not to use any UI interaction in logic classes). Good example on how tests can make code cleaner, too ;)

How can I write output from a unit test?

Try using TestContext.WriteLine() which outputs text in test results.

Example:

[TestClass]
public class UnitTest1
{
private TestContext testContextInstance;

/// <summary>
/// Gets or sets the test context which provides
/// information about and functionality for the current test run.
/// </summary>
public TestContext TestContext
{
get { return testContextInstance; }
set { testContextInstance = value; }
}

[TestMethod]
public void TestMethod1()
{
TestContext.WriteLine("Message...");
}
}

The "magic" is described in MSDN:

To use TestContext, create a member and property within your test class [...] The test framework automatically sets the property, which you can then use in unit tests.

Writing real-time output to a window or text pane during MSTEST

System.Diagnostics.Debug.WriteLine()

will be captured by the Visual Studio Output Window if you run in Debug mode and this should not depend on test execution stage (start/end of a test), so it should be tracked in debug output as soon as executed.

Such kind of output also could be captured and filtered by tools like DbgView

EDIT: answer to comment

I've created MSTest test and able to observe in Debug Window how each new line comes up per each second: (In the output window you can choose between Build/Debug, please ensure you've selected Debug option in drop down list)

[TestMethod]
public void TestMethod1()
{
int i = 10;

while(i-- > 0)
{
Thread.Sleep(1000);
Debug.WriteLine("Step #" + i);
}
}

The test must be run from the Test\Debug\Tests In Current Context menu. The Run Tests option from the right-click context menu will not work.

check output in MSTest unit test

I liked JaredPar's idea but I didn't want to pass in Console.Out and Console.Error to every helper output method I had. However, my output does go through a single class, so I just set a couple static fields in it:

internal static TextWriter _stdOut = Console.Out;
internal static TextWriter _stdErr = Console.Error;

I updated my output methods in the output handler class to make use of these fields. I then updated that project's AssemblyInfo.cs to include:

[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("MyTestProject")]

This way, I can override _stdOut and _stdErr in my test methods, call my method to be tested (which uses my output handling class), and confirm the output I expected.

OutputHandler._stdOut = new StringWriter();
MySnazzyMethod("input", 1, 'c');
OutputHandler._stdOut.Flush();
string expected = "expected output";
string stdout = OutputHandler._stdOut.ToString().Trim(new[] { '\r', '\n' });
Assert.IsFalse(string.IsNullOrEmpty(stdout));
Assert.AreEqual(expected, stdout);


Related Topics



Leave a reply



Submit