Tuesday, July 29, 2008

Testing and Debugging the Project :

Now you will create and run a test for the project using JUnit and then run it in the IDE's debugger to check for errors.

In the JUnit test, you will test the LibClass by passing a phrase to the acrostic method and using an assertion to indicate what you think the result should be.

Creating JUnit Tests>>Right-click the LibClass.java node in the Projects window and choose Tools >Create JUnit Tests (Ctrl-Shift-U). 

If this is the first time you have created JUnit tests in the IDE, you will be prompted with the Select JUnit Version dialog box. Press Enter to select JUnit 4.x and continue to the Create Tests dialog box.

In the Create Tests dialog box, click OK to run the command with the default options. The IDE creates the org.me.mylib package and the LibClassTest.java file in a separate test folder. You can find this file by expanding the Test Packages node and the org.me.mylib subnode.

In LibClassTest.java, delete the body of the public void acrostic() method. 

In place of the deleted lines, type or paste in the following: 

System.err.println("Running testAcrostic...");
String result = LibClass.acrostic(new String[]
  {"fnord", "polly", "tropism"});
  assertEquals("Correct value", "foo", result);

Save the file by pressing Ctrl-S. 

Running JUnit Tests>>Select the MyLib project node and choose Run > Test "MyLib" (Alt-F6).

The MyLib (test) tab opens in the Output window. The JUnit test cases are compiled and run.

The JUnit test result shows that the test passes. 

You can also run a single test file rather than testing the entire project.

Select the LibClass.java tab in the Source Editor and choose Run > Run File > Test "LibClass.java" from the Run menu. 

The JUnit API documentation is available from the IDE. Choose Help > Javadoc References > JUnit API.

You can learn more about JUnit by visiting http://www.junit.org 

Debugging the Project :

In the LibClass.java file, go to the acrostic method and place the insertion point anywhere inside b.append(args[i].charAt(i));. Then press Ctrl-F8 to set a breakpoint. 

Choose Run > Debug Main Project (Ctrl-F5). The IDE opens the Debugger windows and runs the project in the debugger until the breakpoint is reached. 

Select the Local Variables window and expand the args node. The array of strings contains the phrase you entered as the command arguments. 

Click Step Into (F7) in the toolbar to step through the program and watch the acrostic being constructed. 

When the program reaches the end, the debugger windows close.

No comments: