AB Kolan AB Kolan - 1 year ago 71
C# Question

"Hello World" - The TDD way?

Well I have been thinking about this for a while, ever since I was introduced to TDD.
Which would be the best way to build a "Hello World" application ? which would print "Hello World" on the console - using Test Driven Development.

What would my Tests look like ? and Around what classes ?

Request: No "wikipedia-like" links to what TDD is, I'm familiar with TDD. Just curious about how this can be tackled.

Answer Source

You need to hide the Console behind a interface. (This could be considered to be useful anyway)

Write a Test

public void HelloWorld_WritesHelloWorldToConsole()
  // Arrange
  IConsole consoleMock = MockRepository.CreateMock<IConsole>();

  // primitive injection of the console
  Program.Console = consoleMock;

  // Act

  // Assert
  consoleMock.AssertWasCalled(x => x.WriteLine("Hello World"));

Write the program

public static class Program
  public static IConsole Console { get; set; }

  // method that does the "logic"
  public static void HelloWorld()
    Console.WriteLine("Hello World");

  // setup real environment
  public static void Main()
    Console = new RealConsoleImplementation();

Refactor to something more useful ;-)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download