Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"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.

like image 233
abhilash Avatar asked Apr 27 '09 14:04

abhilash


2 Answers

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

Write a Test

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

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

  // Act
  Program.HelloWorld();

  // 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();
    HelloWorld();
  }
}

Refactor to something more useful ;-)

like image 170
Stefan Steinegger Avatar answered Sep 20 '22 04:09

Stefan Steinegger


Presenter-View? (model doesn't seem strictly necessary)

View would be a class that passes the output to the console (simple single-line methods)

Presenter is the interface that calls view.ShowText("Hello World"), you can test this by providing a stub view.

For productivity though, I'd just write the damn program :)

A single test should suffice (in pseudocode):

IView view = Stub<IView>();
Expect( view.ShowText("Hello World") );

Presenter p = new Presenter( view );
p.Show();

Assert.IsTrue( view.MethodsCalled );
like image 21
Lennaert Avatar answered Sep 21 '22 04:09

Lennaert