Home > Articles > Programming > Java

  • Print
  • + Share This
Like this article? We recommend

Start Testing

The unit testing functionality is defined in the junit.framework package. At a very basic level, the object of interest is TestCase. This is called the command object that abstracts the notion of an operation that we want to perform. Each TestCase is identified by a name. A developer extends the TestCase object with its own custom test object. This object can define any number of tests with the standard signature of public void testMethodName(). The JUnit framework uses reflection to call all methods with the name testMethodName(). Within each test method, you can invoke a number of asserts to compare the actual results with the expected results. For example:

assertTrue(myCollection.isEmpty());
assertNotNull(mySession);
assertEquals(1, queryResult.size());
assertSame(myObject1, myObject2);

Each of the above calls is simple and extremely powerful because it allows a developer to express the expected output very concisely.

So, let's create our first test object:

package junittest;

import java.util.*;

//import the junit.framework package
import junit.framework.*;

// extend the TestCase class
public class MyTest extends TestCase {

//pass the name of the test to the super class
  public MyTest(String name) {
    super(name);
  }

//define any number of tests in methods with the signature 
//public void testMethodName()
public void testEmptyCollection() {
    Collection myCollection = new Vector();
    assertTrue(myCollection.isEmpty());
  }

//define a test suite – this allows the framework to use 
// Java reflection API to discover the names of the test methods
public static Test suite() {
    return new TestSuite(MyTest.class);
  }

//define the main method for the class to invoke the runner
public static void main(String args[]) {
    junit.textui.TestRunner.run(suite());
  }
}

Compile the above class and run it from the command prompt (see Figure 2).

Figure 2Figure 2 Console output from running the test.

As shown in Figure 2, the test runs successfully. To view the same tests using the graphical test runner, type the following in the command prompt:

java junit.swingui.TestRunner junittest.MyTest

This displays the tests in the swing-based GUI test runner. A green bar indicates that all the tests have been successful. A failed test is indicated with a red bar.

  • + Share This
  • 🔖 Save To Your Account