Introduction
I needed to test a method which writes to the Console to validate the output. It is not hard to change the default console output and check the result. However, you may forget to return the original output at the end. So let's take a look at my solution.
Let's say we have the following class we want to test:
using System;
namespace ConsoleLogger
{
public class DummyClass
{
public void WriteToConsole(string text)
{
Console.Write(text);
}
}
}
I have created a small helper class to redirect the output to a StringWriter
:
using System;
using System.IO;
namespace ConsoleLogger.Tests
{
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();
}
}
}
Now let's write the unit test:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ConsoleLogger.Tests
{
[TestClass]
public class DummyClassTest
{
[TestMethod]
public void WriteToConsoleTest()
{
var currentConsoleOut = Console.Out;
DummyClass target = new DummyClass();
string text = "Hello";
using (var consoleOutput = new ConsoleOutput())
{
target.WriteToConsole(text);
Assert.AreEqual(text, consoleOutput.GetOuput());
}
Assert.AreEqual(currentConsoleOut, Console.Out);
}
}
}
This way, we are sure that the original output will be restored and it's easy to get the output from the console.
You can find the sample here.
CodeProject