One of the XUnit frameworks, it is an open source, lightweight regression testing framework for Java. Written by Erich Gamma and Kent Beck and released under the IBM Public License.

Writing Test Classes

To write a JUnit test, you normally extend the TestCase class, adding public void methods beginning with test, like so:

    public void testGetInvalidIndex() {
        Object x = foo.get(-1);
        assertNull(x);
    }

JUnit provides a number of assert methods: assertTrue, assertEquals, assertNull, assertNotNull, and so on, as well as a fail() method which is the same as assertTrue(false). A failed assertion causes an AssertionFailedError to be thrown, which JUnit's TestRunner catches.

You may optionally override the protected setUp() and tearDown() methods to do common initialization and cleanup; JUnit calls these methods before and after each individual test, respectively.

Running Tests

The test methods on a class are discovered automagically through reflection at runtime by the TestRunner. Normally one builds up TestSuite classes which bring together a number of TestCases. There is little worse than finding out that dozens of broken tests were never caught because some idiot coder, often me, added a TestCase class but forgot to add it to the suite. This is a Bad Thing. I eliminated this headache by creating a DynamicTestRunner that (once again) automagically scours the classpath for all TestCase classes.

There are three TestRunner implementations supplied with JUnit: the textui, swingui, and awtui versions. The Swing version a LoadingTestRunner by default which means you can keep the TestRunner window open while modifying some code, compile the code, click Run in the TestRunner, and it will automagically (there's a lot of magic, isn't there?) reload the modified classes and run the tests.

The TestRunners report the total number of tests run, the number of failures, and the number of errors. Failures are tests with failed assertions ("anticipated failures"), while errors are tests who threw an uncaught exception ("unanticipated failures").

Log in or register to write something here or to contact authors.