[ C:TaPiC ]
Lab 1 Lab 2 Lab 3 Lab 4 Lab 5 Lab 6 Lab 7 Lab 8
The following piece of code is based on the example given in (Kernighan and Ritchie, 1978).
namespace OpenEd.Lab0006
{
public class Hello
{
public static void Main()
{
Console.Write("hello, world\n");
}
}
}
Now we will look at how we can split this up so that we can use a test driven approach. There is not much to test here and because of this, in the same way hello world requires many things to be in place, so too making hello world test driven will cover much of the components of test driven development.
To be able to test the program we split the user interface and the functional part of the program. You will see later that once we have tested the functional part we can use it with different user interfaces.
using System;
using System.IO;
namespace OpenEd.Lab0006
{
public class Hello
{
private TextWriter writer;
public Hello(TextWriter writer)
{
this.writer = writer;
}
public void Run()
{
writer.Write("hello, world\n");
}
}
}
Now we write a test (this isn't the normal order of things, we would normally write the test first).
using System; using System.IO; using System.Text; using NUnit.Framework;
namespace OpenEd.Lab0006
{
[TestFixture]
public class HelloTest
{
[Test]
public void Run()
{
StringBuilder sb = new StringBuilder();
StringWriter writer = new StringWriter(sb);
Hello hello = new Hello(writer);
hello.Run();
Assert.AreEqual("hello, world\n", sb.ToString());
}
}
}
We run the test and it passes! Now we need to connect the tested assembly to the console:
using System;
namespace OpenEd.Lab0006
{
public class Runner
{
public static void Main()
{
Hello hello = new Hello(Console.Out);
hello.Run();
}
{
}
So far the approach to writing console applications has been fairly ad-hoc. A conosole application has a well defined structure and we can use this to develop applications that implement a common interface.
using System;
using System.IO;
namespace OpenEd.Lab0006
{
public interface IConsoleApp {
int Run(TextReader inReader, TextWriter outWriter, TextWriter errWriter, string[] args);
}
}
© 2009 Novell, Inc. All Rights Reserved.