views:

634

answers:

10

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.

A: 

I guess something like this:

using NUnit.Framework;
using System.Diagnostics;

[TestFixture]
public class MyTestClass {
    [Test]
    public void SayHello() {
     string greet = "Hello World!";
     Debug.WriteLine(greet);
     Assert.AreEqual("Hello World!", greet);
    }
}
Jhonny D. Cano -Leftware-
Thanks for the answer. But what if the classes and tests were different ? And I want to go beyond string equality Test?
AB Kolan
What exactly do you want to achieve?
Jhonny D. Cano -Leftware-
+4  A: 

Well...I've not seen a TDD version of hello world. But, to see a similarly simple problem that's been approached with TDD and manageability in mind, you could take a look at Enterprise FizzBuzz (code). At least this will allow you to see the level of over-engineering you could possibly achieve in a hello world.

dustyburwell
Thanks ascalonx, Well, thinking of it, even i have yet to encounter a TDD version of Hello World.
AB Kolan
+5  A: 

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 );
Lennaert
MVP for Hello World ? Overkill!
Gishu
Hey, he wanted it unit tested, why not go all the way? ;)
Lennaert
+1  A: 

In java you could capture ("redirect") the System.out stream and read its contents. I'm sure the same could be done in C#. It's only a few lines of code in java, so I'm sure it won't be much more in C#

krosenvold
You can set the output stream to any TextWriter so the following should work.TextWriter output = new StringWriter();Console.SetOut(output);//Call your hello world method hereAssert("Hello World", output.ToString());
Martin Harris
Thanks. That's not much of a test fixture ;)
krosenvold
+3  A: 

Pseudo-code:

  • Create a mock of something that accepts a stream.
  • Invoke helloworld onto this mock through some sort of dependency injection (Like a constructor argument).
  • Verify that the "Hello World" string was streamed into your mock.

In production code, you use the prompt instead of the mock.

Rule of thumb:

  • Define your success criteria in how the component interacts with other stuff, not just how it interacts with you. TDD focuses on external behavior.
  • Set up the environment (mocks) to handle the chain of events.
  • Run it.
  • Verify.
Tormod
+12  A: 

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

Stefan Steinegger
I would just inject and mock System.IO.TextWriter, which is an abstract type implemented by `System.Console.Out`. No need to write `IConsole` and `RealConsoleImplementation` that way
Wim Coenen
It depends. I like to implement against interfaces. If there isn't any, I write sometimes my own, as small as I need it. Why using a large, general purpose interface, if you only need a few simple methods? And abstract base classes include logic. The caller should really not care who is implementing "WriteLine".
Stefan Steinegger
A: 

Something like this: http://weblogs.asp.net/sfeldman/archive/2008/12/12/quot-hello-world-quot-tdd-style.aspx? It looks useful, can't say I've ever implemented HelloWorld in TDD, I tend to develop server side code which is much more ameanable to TDD.

Steve Haigh
+2  A: 

A very interesting question. I'm not a huge TDD user, but I'll throw some thoughts out.

I'll assume that the application that you want to test is this:

public static void Main()
{
    Console.WriteLine("Hello World");
}

Now, since I can't think of any good way of testing this directly I'd break out the writing task into an interface.

public interface IOutputWriter
{
    void WriteLine(string line);
}

public class ConsoleWriter : IOutputWriter
{
    public void WriteLine(string line)
    {
        Console.WriteLine(line);
    }
}

And break the application down like this

public static void Main()
{
    IOutputWriter consoleOut = new ConsoleWriter();
    WriteHelloWorldToOutput(consoleOut);
}

public static void WriteHelloWorldToOutput(IOutputWriter output)
{
    output.WriteLine("Hello World");
}

Now you have an injection point to the method that allows you to use the mocking framework of your choice to assert that the WriteLine method is called with the "Hello World" parameter.

Problems that I have left unsolved (and I'd be interested in input):

  1. How to test the ConsoleWriter class, I guess you still need some UI testing framework to achieve this, and if you had that then the whole problem in moot anyway...

  2. Testing the main method.

  3. Why I feel like I've achieved something by changing one line of untested code into seven lines of code, only one of which is actually tested (though I guess coverage has gone up)

Martin Harris
+1  A: 

I really have to object to the question! All methodologies have their place, and TDD is good in a lot of places. But user interfaces is the first place I really back off from TDD. This, in my humble opinion is one of the best justifications of the MVC design pattern: test the heck out of your models and controller programmatically; visually inspect your view. What you're talking about is hard-coding the data "Hello World" and testing that it makes it to the console. To do this test in the same source language, you pretty much have to dummy the console object, which is the only object that does anything at all.

Alternately, you can script your test in bash:

echo `java HelloWorldProgram`|grep -c "^Hello World$"

A bit difficult to add to a JUnit test suite, but something tells me that was never the plan....

David Berger
A: 

I agree with David Berger; separate off the interface, and test the model. It seems like the "model" in this case is a simple class that returns "Hello, world!". The test would look like this (in Java):

  Greeter greeter = new Greeter();
  assertEquals("Hello World!", greeter.greet());

I've created a video of solving Hello World TDD style at http://www.youtube.com/watch?v=oXYw-ppevA4 , and a write up at http://ziroby.wordpress.com/2010/04/18/tdd_hello_world/ .

Ron Romero