Sunday, August 29, 2010

Test Drive Hello World

Earlier this week during a discussion on Test Driven Development TDD I commented to an associate that "once the TDD mindset takes a hold of you, you will find yourself writing the test before you write a single line of code even for something as trivial as hello world." My friend paused and asked how and I responded, well I would write a test to look at Standard Output and assert that it contained 'hello world'. The test will fail, then I would write to the Standard Output and watch the test failed. We moved on to other topics but in the back of my head a voice said 'why not try it out'

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);
}

No comments: