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.