Grabbing the output sent to Console.Out from within a unit test?

C#Unit TestingConsoleNunit

C# Problem Overview


I am building a unit test in C# with NUnit, and I'd like to test that the main program actually outputs the right output depending on the command line arguments.

Is there a way from an NUnit test method that calls Program.Main(...) to grab everything written to Console.Out and Console.Error so that I can verify against it?

C# Solutions


Solution 1 - C#

You can redirect Console.In, Console.Out and Console.Error to custom StringWriters, like this

[TestMethod]
public void ValidateConsoleOutput()
{
    using (StringWriter sw = new StringWriter())
    {
        Console.SetOut(sw);

        ConsoleUser cu = new ConsoleUser();
        cu.DoWork();

        string expected = string.Format("Ploeh{0}", Environment.NewLine);
        Assert.AreEqual<string>(expected, sw.ToString());
    }
}

See this blog post for full details.

Solution 2 - C#

You can use this simple class to get the output with a using statement:

public class ConsoleOutput : IDisposable
{
    private StringWriter stringWriter;
    private TextWriter originalOutput;

    public ConsoleOutput()
    {
        stringWriter = new StringWriter();
        originalOutput = Console.Out;
        Console.SetOut(stringWriter);
    }

    public string GetOuput()
    {
        return stringWriter.ToString();
    }

    public void Dispose()
    {
        Console.SetOut(originalOutput);
        stringWriter.Dispose();
    }
}

Here is an example how to use it:

using (var consoleOutput = new ConsoleOutput())
{
    target.WriteToConsole(text);

    Assert.AreEqual(text, consoleOutput.GetOuput());
}

you can find more detailed information and a working code sample on my blog post here - Getting console output within a unit test.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLasse V. KarlsenView Question on Stackoverflow
Solution 1 - C#Mark SeemannView Answer on Stackoverflow
Solution 2 - C#Vasil TrifonovView Answer on Stackoverflow