Generate Test Cases

Throughout CS2102 I will stress the importance of designing test cases incrementally as you design your program. This technique helps you develop more robust code by decomposing the complex process of testing into manageable chunks. Eclipse, once again, can help because it comes pre-packaged with the well-known JUnit testing framework. The essential idea is that each time you add functionality to your program, you also add a test case to determine whether you succeeded in your sub-task. For more information on using JUnit and Eclipse, read here.

The description of JUnit is presented here in the context of the lab files that you will be creating for Lab 2.

Select the Precinct.java source file from the package explorer and right click to find the New->JUnit Test Case option.

When you exercise this option for the first time, Eclipse will prompt you with a question, to which you answer "Yes".

A New JUnit Test Case wizard appears. Change the Name of the test case to "Precinct" because that is the functionality we intend to test; when done, click on Finish.

You should now see some added files to your Eclipse project.

We must now construct the details of the test case PrecinctTest. Change its text to be as shown below. JUnit tries to be as simple and helpful as possible, and we do not need to discuss all of its complex details here. What you need to know is that

Within the method body, you can assert various claims about the particular method you are trying to test. The most common ones are going to be:

Once you have determined that a test case fails, you can then say:

Working with JUnit is best described by example. So, within the Precinct class, we need to test that the instance methods we have written (add and remove) work properly. Specifically, add the instance method "testAdd" to the Precinct class. Now that we have created this test case, we must show how to execute it.

Right-click on PrecinctTest class (the JUnit test case you just created) and select menu item Run As -> JUnit Test

You will see a new tabbed panel appear on the left, containing information about the trace runs.

Is this test case sufficient for Precinct? No. But it is just one of many. And if you follow a test-driven approach, you will find yourself creating test cases for each instance method that you add to a Java class. Note that if the test case had failed, information would appear in the tabbed pane showing you exactly what had gone wrong, and the line number of the code where the problem occured.