Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Mail Systems
Eclipse Documentation

How To Guides
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Problem Solutions




Thinking in Java
Prev Contents / Index Next


Although the testing framework just described allows you to verify program output simply and easily, in some cases you may want to perform more extensive functionality testing on a program. JUnit, available at, is a quickly emerging standard for writing repeatable tests for Java programs, and provides both simple and complex testing.

The original JUnit was presumably based on JDK 1.0 and thus could not make use of Java’s reflection facilities. As a result, writing unit tests with the old JUnit was a rather busy and wordy activity, and I found the design to be unpleasant. Because of this, I wrote my own unit testing framework for Java,[90] going to the other extreme and “doing the simplest thing that could possibly work.”[91] Since then, JUnit has been modified and uses reflection to greatly simplify the process of writing unit test code. Although you still have the option of writing code the “old” way with test suites and all the other complex details, I believe that in the great majority of cases you can follow the simple approach shown here (and make your life more pleasant).

In the simplest approach to using JUnit, you put all your tests in a subclass of TestCase. Each test must be public, take no arguments, return void, and have a method name beginning with the word “test.” Junit’s reflection will identify these methods as individual tests and set up and run them one at a time, taking measures to avoid side effects between the tests.

Traditionally, the setUp( ) method creates and initializes a common set of objects that will be used in all the tests; however, you can also just put all such initialization in the constructor for the test class. JUnit creates an object for each test to ensure there will be no side effects between test runs. However, all the objects for all the tests are created at once (rather than creating the object right before the test), so the only difference between using setUp( ) and the constructor is that setUp( ) is called directly before the test. In most situations this will not be an issue, and you can use the constructor approach for simplicity.

If you need to perform any cleanup after each test (if you modify any statics that need to be restored, open files that need to be closed, open network connections, etc.), you write a tearDown( ) method. This is also optional.

The following example uses this simple approach to create JUnit tests that exercise the standard Java ArrayList class. To trace how JUnit creates and cleans up its test objects, CountedList is inherited from ArrayList and tracking information is added:

// Simple use of JUnit to test ArrayList
// {Depends: junit.jar}
import java.util.*;
import junit.framework.*;

// So we can see the list objects being created,
// and keep track of when they are cleaned up:
class CountedList extends ArrayList {
  private static int counter = 0;
  private int id = counter++;
  public CountedList() {
    System.out.println("CountedList #" + id);
  public int getId() { return id; }

public class JUnitDemo extends TestCase {
  private static com.bruceeckel.simpletest.Test monitor =
    new com.bruceeckel.simpletest.Test();
  private CountedList list = new CountedList();
  // You can use the constructor instead of setUp():
  public JUnitDemo(String name) {
    for(int i = 0; i < 3; i++)
      list.add("" + i);
  // Thus, setUp() is optional, but is run right
  // before the test:
  protected void setUp() {
    System.out.println("Set up for " + list.getId());
  // tearDown() is also optional, and is called after
  // each test. setUp() and tearDown() can be either
  // protected or public:
  public void tearDown() {
    System.out.println("Tearing down " + list.getId());
  // All tests have method names beginning with "test":
  public void testInsert() {
    System.out.println("Running testInsert()");
    assertEquals(list.size(), 3);
    list.add(1, "Insert");
    assertEquals(list.size(), 4);
    assertEquals(list.get(1), "Insert");
  public void testReplace() {
    System.out.println("Running testReplace()");
    assertEquals(list.size(), 3);
    list.set(1, "Replace");
    assertEquals(list.size(), 3);
    assertEquals(list.get(1), "Replace");
  // A "helper" method to reduce code duplication. As long
  // as the name doesn't start with "test," it will not
  // be automatically executed by JUnit.
  private void compare(ArrayList lst, String[] strs) {
    Object[] array = lst.toArray();
    assertTrue("Arrays not the same length",
      array.length == strs.length);
    for(int i = 0; i < array.length; i++)
      assertEquals(strs[i], (String)array[i]);
  public void testOrder() {
    System.out.println("Running testOrder()");
    compare(list, new String[] { "0", "1", "2" });
  public void testRemove() {
    System.out.println("Running testRemove()");
    assertEquals(list.size(), 3);
    assertEquals(list.size(), 2);
    compare(list, new String[] { "0", "2" });
  public void testAddAll() {
    System.out.println("Running testAddAll()");
    list.addAll(Arrays.asList(new Object[] {
      "An", "African", "Swallow"}));
    assertEquals(list.size(), 6);
    compare(list, new String[] { "0", "1", "2",
       "An", "African", "Swallow" });
  public static void main(String[] args) {
    // Invoke JUnit on the class:;
    monitor.expect(new String[] {
      "CountedList #0",
      "CountedList #1",
      "CountedList #2",
      "CountedList #3",
      "CountedList #4",
      // '.' indicates the beginning of each test:
      ".Set up for 0",
      "Running testInsert()",
      "Tearing down 0",
      ".Set up for 1",
      "Running testReplace()",
      "Tearing down 1",
      ".Set up for 2",
      "Running testOrder()",
      "Tearing down 2",
      ".Set up for 3",
      "Running testRemove()",
      "Tearing down 3",
      ".Set up for 4",
      "Running testAddAll()",
      "Tearing down 4",
      "%% Time: .*",
      "OK (5 tests)",
} ///:~

To set up unit testing, you must only import junit.framework.* and extend TestCase, as JUnitDemo does. In addition, you must create a constructor that takes a String argument and passes it to its super constructor.

For each test, a new JUnitDemo object will be created, and thus all the non-static members will also be created. This means a new CountedList object (list) will be created and initialized for each test, since it is a field of JUnitDemo. In addition, the constructor will be called for each test, so list will be initialized with the strings “0”, “1”, and “2” before each test is run.

To observe the behavior of setUp( ) and tearDown( ), these methods are created to display information about the test that’s being initialized or cleaned up. Note that the base-class methods are protected, so the overridden methods may be either protected or public.

testInsert( ) and testReplace( ) demonstrate typical test methods, since they follow the required signature and naming convention. JUnit discovers these methods using reflection and runs each one as a test. Inside the methods, you perform any desired operations and use JUnit assertion methods (which all start with the name “assert”) to verify the correctness of your tests (the full range of “assert” statements can be found in the JUnit javadocs for junit.framework.Assert). If the assertion fails, the expression and values that caused the failure will be displayed. This is usually enough, but you can also use the overloaded version of each JUnit assertion statement and include a String that will be printed if the assertion fails.

The assertion statements are not required; you can also just run the test without assertions and consider it a success if no exceptions are thrown.

The compare( ) method is an example of a “helper” method that is not executed by JUnit but instead is used by other tests in the class. As long as the method name doesn’t begin with “test,” JUnit doesn’t run it or expect it to have a particular signature. Here, compare( ) is private to emphasize that it is only used within the test class, but it could also be public. The remaining test methods eliminate duplicate code by refactoring it into the compare( ) method.

To execute the JUnit tests, the static method ) is invoked in main( ). This method is handed the class that contains the collection of tests, and it automatically sets up and runs all the tests. From the expect( ) output, you can see that all the objects needed to run all the tests are created first, in a batch—this is where the construction happens.[92] Before each test, the setUp( ) method is called. Then the test is run, followed by the tearDown( ) method. JUnit demarcates each test with a ‘.’.

Although you can probably survive easily by only using the simplest approach to JUnit as shown in the preceding example, JUnit was originally designed with a plethora of complicated structures. If you are curious, you can easily learn more about them, because the JUnit download from comes with documentation and tutorials.
Thinking in Java
Prev Contents / Index Next

   Reproduced courtesy of Bruce Eckel, MindView, Inc. Design by Interspire