next up previous
Next: 1.8.5 Conclusion Up: 1.8 Unit Testing in Previous: 1.8.3 Write The Tests

1.8.4 Unit Testing and JUnit

JUnit has provided a powerful facility for running unit tests in Java. In fact, the code for DrJava itself is tested using an extensive suite of JUnit tests. Of the 53,000 lines of code that comprise the latest build of DrJava, 16,000 lines consist of unit tests. As part of our build process, we ensure that these tests must be run before any change to the code is committed.

To help users test their own programs, support for running JUnit tests is included in DrJava. To use JUnit on a test file, the following programming conventions must be used:

At the top of the file, include:

import.junit.framework.TestCase;
This line is an import statement that tells Java to include the JUnit class TestCase in the namespace of the file. The main class of the file must:

The test methods of this class (methods to be run automatically when the Test command is invoked) must:

Test methods in this class can call any of the following methods:

If there is any setup work to be done before running the tests (such as initializing instance variables), do it in the body of a method with the following contract: protected void setUp() This method is automatically run before each test in the class. There is a corresponding method, tearDown() that is called after each method. tearDown() is useful for releasing shared resources, such as open files or database locks.

Alternatively, a test suite can be constructed to invoke a series of test methods under programmer control with a method of the form:

public static Test suite() {
TestSuite suite = new TestSuite();
suite.addTest(new classname("methodname");
...
return suite;
}

It is then also necessary to import TestSuite and Test from junit.framework. There is also a version of the addTest() method that takes a Test, so test suites can be composed.

To start JUnit on a TestCase in DrJava, simply click the Test button (or choose "Test Using JUnit" from the Tools menu) when a valid test file is open, and DrJava will run the tests and display any test failures in the "Test Output" tab at the bottom of the window, much the same as compiler errors are displayed.


next up previous
Next: 1.8.5 Conclusion Up: 1.8 Unit Testing in Previous: 1.8.3 Write The Tests
Corky Cartwright 2002-08-09