views:

60

answers:

4

I have been learning about TDD (using JUnit) and I have a doubt about how to go about testing void methods, in which case I can't directly use something like an assertTrue() on the return value of a method.. For example, say I have a simple console based application, and a part of it prints a menu on screen, say using this method:

public void printMenu()
{
   System.out.println("Menu:");
   System.out.println("1. Option ONE");
   System.out.println("2. Option TWO");
   System.out.println("3. Exit");
}

My question is, do I actually have to test this method?? And if so, how should I do it?

A: 

capture the console output and compare to expectations

Steven A. Lowe
+2  A: 

It is difficult to unit test a method which relies on static method calls. It is not a matter of returning something or void. What you could do is abstract the printing into an interface and have your class depend on this interface (using constructor injection for example):

private SomePrinterInterface _printer;

public void printMenu()
{
   _printer.println("Menu:");
   _printer.println("1. Option ONE");
   _printer.println("2. Option TWO");
   _printer.println("3. Exit");
}

In your unit test you could mock the interface and verify if correct methods have been called on it. This way you could test the printMenu in independently.

Darin Dimitrov
A: 

You can not unit test this method.

This method does no logic or processing that you need to unit test.

If you need to unit test the Print Menu, you can consider outputing the result to a text file. Then read the text file and compare the menu texts..

J Angwenyi
A: 

First: testing UI is hard. Some people don't bother testing things like this because it is very difficult to write meaningful tests that aren't fragile to the point of uselessness. I wouldn't bother testing this method.

But:

If you want to test menu generation, because your menu code is complex and you need ways to ensure that it works, you have a couple choices.

  1. Refactor your method so that it accepts the output stream as a parameter, then pass in an output stream whose contents you can inspect. You might also be able to redirect System.out to achieve this.
  2. Refactor your method so that the menu is generated as a bunch of objects, then printed separately. You can inspect and verify those objects.
Mr. Shiny and New