JUnit is a unit testing framework for Java. These materials are based on JUnit 4.

Creating and Running a Test Case

Everything in Java revolves around classes. Previously, you’ve seen classes used to implement drivers . For this lab you will create classes used to implement test-cases . To create a JUnit test case class in Eclipse, do the following:

  1. Click mouse-right on the package of the project where you want the new class to go.
  2. Choose “New”-“JUnit Test Case”.
  3. Choose “New JUnit 4 test”.
  4. Make sure the package name is correct.
  5. Enter the appropriate class name. JUnit test class names must end with Test.
  6. Press the Finish button.

This creates a new test case class to which can add test cases, which are implemented as methods. For example, the following case contains two test statements that verify that the boolean expression 1==1 is true, the second that the integer 1 equals 1, and the third that the double 1.0 equals 1.0:

@Test
public void doNothingInterestingTest() {
	assertTrue(1==1);
	assertEquals(1, 1);
	assertEquals(1.0, 1.0, 1e-3);
}

Note that assertEquals() tests of double equivalence require a third parameter that specifies an error tolerance. If any of these assertions fail, then JUnit automatically signals a unit test failure.

A test class is not a typical Java application so you don’t run it as a Java Application. Instead, you run it as a JUnit test case (e.g., by choosing “Run”-“Run As”-“JUnit test case” Eclipse displays a successful JUnit test as shown here:

JUnit output for a successful unit test

Here, the JUnit output is show in the panel on the bottom right. Note that a successful test case like this one displays a green bar, on the right, and a list of test cases that it ran, on the left. Because Eclipse allows you to run all of your test cases or a sub-set of them, make sure that when you run your test that all the test cases you expected to run are listed on the left.

Do this...

Create and run a new test class with a single test case method that verifies the following:

Failing a Test

If any one of the test cases, JUnit displays a red bar and an error message on the right. You can jump directly to the test statement that caused the error using Eclipse’s “Go To File” tool (double-click on the error line in the JUnit output). The following image shows the results for a failed test of 1==2.

JUnit output for a failed unit test

Do this...

Modify your test case so that it fails, run it and note the output you get. Make sure that you can jump to the line that caused the error.

Back to the top of this page