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:
public classname(String name) { super(name); }Note: If you forget to do this, you will get an error message that begins:
"TestCase() is not public..."These conventions are necessary is because class TestCase has a single public constructor, and this constructor takes a String as its parameter. As with all Java classes, we have to call a constructor of the super-class within the constructor of the extending class. By default, the zero-argument will be called implicitly, but there is no zero-argument constructor to call on class TestCase.
The test methods of this class (methods to be run automatically when the Test command is invoked) must:
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.