Here is chronology of that trial:
I first wrote the following unit test to capture Standard Output
[TestMethod]
public void TestSayHello()
{
string logFile = "test_log.txt";
string result;
using (StreamWriter writer = new StreamWriter(logFile))
{
Console.SetOut(writer);
SayHello();
}
using (StreamReader reader = new StreamReader(logFile))
{
result = reader.ReadLine();
}
Assert.AreEqual("Hello World", result);
}
Next I wrot the following method to get my unit test to pass
private void SayHello()
{
Console.WriteLine("Hello World");
}
I next DRYed the unit test by introducing the following helper method
private string CaptureStandardOutput(Action perfromAction)
{
string logFile = "test_log.txt";
string result;
using (StreamWriter writer = new StreamWriter(logFile))
{
Console.SetOut(writer);
perfromAction();
}
using (StreamReader reader = new StreamReader(logFile))
{
result = reader.ReadToEnd();
}
return result;
}
Which in turn cleaned up the unit test as follows
[TestMethod]
public void TestSayHello()
{
string result = CaptureStandardOutput(SayHello);
Assert.AreEqual("Hello World\r\n", result);
}