views:

148

answers:

1

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 a NUnit test method, that calls Program.Main(...) to grab everything written to Console.Out and Console.Error so that I can verify against it?

+6  A: 

You can redirect Console In, Out and 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.

Mark Seemann
Worked like a charm, thanks!
Lasse V. Karlsen
If you use Resharper you will lose output screen for all further tests by doing this :(
HeavyWave