Creating a JUnit Test Case

A test case class has one or more methods that perform tests by calling JUnit assertions. A typical test case will pass test fixture data to the method being tested, and then compare the result with a known value to confirm that it is what is expected. For example:

public void testCountChars()
{
  int expected = 4;
  int actual = fixture1.countChars( 'a' );
  assertEquals( actual, expected );
}

In this test case countChars() is being tested, and the result of the test is checked by assertEquals(), which is one of a variety of assertion methods defined in the JUnit Assert class. The state of the test fixture, fixture1, is established in the setUp() method, which will have been called before the test case is called:

protected void setup() throws Exception
{
  fixture1 = new StringFixture("Goin' to Kansas City, Kansas City, here I come.");
}

To create a JUnit test case class:

  1. In the Navigator, select the project.
  2. Choose File | New to open the New Gallery.
  3. In the Categories tree, expand General and select Unit Tests (JUnit).
  4. In the Items list, double-click Test Case.
  5. Complete the wizard to create the test fixture class. For more information at any time, press F1 or click Help from within the dialog.

    The class created by the wizard will be opened for editing.

  6. Modify the file as needed. In particular:


junit.framework.TestCase
junit.framework.Assert

Creating a JUnit Test for a Generic Java Project
Creating a JUnit Custom Test Fixture
Creating a JUnit Test Suite