GeekLondon.com Help icon Syndication Feed icon 

Hello Tester

A user on the Sun Java forums asked how you'd go about writing a unit test for a Hello World program. Of course a test for Hello World, the definitive simple program, would be significantly more likely to contain bugs than the hello world program itself, so writing a unit test for it is hard to justify. Still, it's an interesting problem, and I enjoyed addressing it. I've copied the resulting code here for future reference and bragging.

Here's the program to test:

public class HelloWorld {
   public static void main(String[] args) {
      System.out.println("Hello World");
   }
}

And here's its Unit Test (using JUnit):

import java.io.ByteArrayOutputStream;

import java.io.PrintStream;
import junit.framework.TestCase;

public class TestHelloWorld extends TestCase {
   public void testHello()
      throws Exception
   {
      // Prepare the expected text
      final String expectedText = "Hello World" + System.getProperty("line.separator");
      final byte[] expectedByteArray = expectedText.getBytes();

      // Prepare the mock print stream for the output
      ByteArrayOutputStream outputStream = new ByteArrayOutputStream(expectedByteArray.length);
      PrintStream out = new PrintStream(outputStream);
      System.setOut(out);

      // Carry out the code
      HelloWorld.main(new String[] { });

      // Obtain the results
      final byte[] actualByteArray = outputStream.toByteArray();

      // Assert that the expected and actual output are equivalent
      assertEquals("Expected and Actual output differs in length",expectedByteArray.length,actualByteArray.length);

      for( int i = 0; i < actualByteArray.length; i++ ) {
         assertEquals("Difference in content",expectedByteArray[i],actualByteArray[i]);
      }
   }
}
Posted at Feb 22, 2007 6:55:06 PM, and last updated Feb 22, 2007 7:07:04 PM