The One-Page Tutorial Series
Carlos
Valcarcel, Chief Architect
Copyright
2003 EinTech, Inc.
EinTech, Inc.
Company
and product names mentioned in The One-Page Tutorialstm are
trademarks or registered trademarks of their respective companies.
public void testMyMethod()
{
MyClass myClass = new
MyClass();
int result =
myClass.myMethod(0);
}
public void testMyMethod()
{
MyClass myClass = new
MyClass();
int result =
myClass.myMethod(0);
assertTrue("result
!= 0", result == 0);
}
Creating a JUnit Test within Eclipse
Copyright 2003, EinTech, Inc.
Level: Introductory
The built-in support Eclipse has for the JUnit testing framework allows developers to write tests faster than ever as many of the tedious aspects of coding a test class and the class to be tested are handled in an automated and efficient fashion. In this article we will cover the basics of JUnit within Eclipse and cover an example of how to grow a JUnit test within a project.
JUnit is a framework for writing test cases. The framework supplies a set of base classes encapsulating a reusable infrastructure that understands what a test case is and how to run the test case in a controlled environment. Once a developer becomes familiar with the basics of the JUnit framework writing test cases not only becomes simple (or at least simpler than before), it becomes trivial.
As of JUnit 3.7 there are 14 classes in the entire framework. In day-to-day use of the framework you only have to worry about class TestCase. Any test case you want to write will extend TestCase to inherit its methods and the methods TestCase inherits from the Assert class. There are two methods to remember from TestCase and seven methods to remember from Assert:
TestCase:
setUp()
tearDown()
Assert:
assertTrue()
assertEquals()
assertNotNull()
assertNull()
assertSame()
assertTrue()
fail()
There are many methods available but the above represent the 20% used 80% of the time.
In TestCase the setUp() and tearDown() methods are useful if there is initialization and clean-up to be done before and after every test. If there is nothing to setup prior to a test being run, or nothing to do after the test has been run, then setUp() and tearDown() can be safely ignored.
If you are looking for an unvarnished example of how to use JUnit from within Eclipse then the One-Page Tutorialtm (OPT) should be all you need. Everything that follows is an explanation of the steps outlined in the OPT.
Start Eclipse and select the Java perspective (press the first button of the toolbar to the left and running down the side of the Eclipse workbench and select Java). If, for whatever reason, Java is not available as a selection then choose Other and select Java from the Select Perspective Dialog.
When Eclipse completes morphing from whatever-perspective-it-was-using to the Java perspective you should see the Package Explorer view to the left, the editor view in the center, the outline view to the right, and the standard output console view to the bottom. If the console is not visible then select the tab marked Console to bring it forward. If the Console tab is not visible then go to the Menu bar and select Window->Show View->Console (Fig. 1).

Figure 1. The Eclipse Workbench – Java Perspective
Any project can have JUnit tests added to it. For this example, create a new project by pressing control-n or from the menu bar use the mouse and select File->New->Java Project. From the New Dialog select Java from the right-hand list and Java Project from the left hand list. Press Next and enter the project name as JUnitExample. Leave the directory set to Use Default unless you have an existing directory where you put your projects. Pressing Next takes us to the Java Settings area. As junit.jar does not appear in the project by default we are going to add it by selecting the Libraries tab and pressing the Add External JARs button (you will have to repeat this step for all of the projects where JUnit tests will be used). A standard file dialog will appear. Navigate to the Eclipse installation directory and go into its plugins directory. Select the org.junit_3.7.0 directory and double-click or press the Open button. Select the junit.jar file and, again, double-click or press the Open button. The junit.jar file should appear in the list of JARs and class folders Eclipse will use when it builds the project (Fig. 2). The project is now configured so press Finish.

Figure 2. The junit.jar file added to the classpath of the JUnitExample project.
Select the JUnitExample project from the Package Explorer. Press control-n and, when the New Dialog appears, select Java and Class from the left and right lists, respectively. In Test Driven Development (TDD) the test class is written first followed by the class definition of the object to be tested. As we will see when we create the JUnit test class, the Eclipse JUnit wizard expects the class definition to already exist. This does not affect the creation of the test cases in any way so do not worry about it.
Enter MyClass as the name of the class being created and press Finish. The class definition should appear in the editor view with a default main(). We will not be using main() in this example so its existence is harmless. Also, notice that both of our classes are being created in the default package space, which is to say, with no package name.
Now we will create the JUnit test case. Press control-n to bring up the New Dialog once again. Press the plus-sign next to Java in the left-hand list to reveal JUnit as a sub-node and select JUnit. In the right-hand list, which now displays TestCase and TestSuite, select TestCase. If you press Next you will find that all of the information needed by the Wizard has already been filled in. The only item of note is the Superclass listed: junit.framework.TestCase (Fig. 3). Press Finish to bring MyClassTest.java into the editor. If MyClassTest.java is not opened in the editor then double-click on it in the Package Explorer view.

Figure 3. The New Dialog with junit.framework.TestCase as the super class.
Both classes (MyClass and MyClassTest) should be free of compile errors. In MyClassTest add the following method:
public void testMyMethod()
{
MyClass myClass = new
MyClass();
int result =
myClass.myMethod(0);
}
Any methods that we want the JUnit framework to run automatically must, by convention, be called test<The name of the method to be tested>(). We have not tested anything yet. All we are doing is beginning to get a feel for the way the API of MyClass will be used in user-defined situations. My current expectation is that myMethod() should return whatever value I pass into it. For our first test we will pass in a zero and expect to get back a zero unharmed.
In the meantime, Eclipse is telling us that a problem exists: clicking once on the light bulb in the left hand margin of the editor tells us that myMethod() does not exist in MyClass. The editor, alerted that you care about this problem when you selected the light bulb, offers to correct the problem by creating a stubbed-out myMethod() in MyClass. Clicking on the light bulb displays the QuickFix window (Fig. 4) which states: “Create method ‘myMethod(..)’ in MyClass”. Double clicking on the suggestion causes MyClass.java to be displayed in the editor with an Eclipse-generated version of myMethod()complete with a method signature that includes an incoming argument of the proper type (an int) and a default return value type of int. If the method were empty the incremental compiler would complain of a syntax error as any method that says it is returning a value must have code that returns something. In order to satisfy the syntactical requirements of the compiler the generated code for myMethod()returns a value of zero. In keeping with the spirit of only coding as much as is needed to pass the test we will leave the code untouched.

Figure 4. The Quick Fix window suggests potential solutions to compiler errors.
Select the MyClassTest.java editor tab to bring the MyClassTest source to the front. Add the line in bold:
public void testMyMethod()
{
MyClass myClass = new
MyClass();
int result =
myClass.myMethod(0);
assertTrue("result
!= 0", result == 0);
}
Method assertTrue() is inherited from Assert. The first argument is the message JUnit will display if the assertion fails and the second argument is a boolean (in this case, the result of the expression result == 0). The call to assertTrue() is given the value of the result == 0 expression and throws an AssertionFailedException if the expression resolves to false. The generated version of myMethod() returns a zero so our test should pass the first time. Check the test by running it: from the menu bar select Run->Run As->2 JUnit Test. Regardless of what is being displayed in the right view the JUnit Test Runner will come up to display the outcome of the test. The Test Runner is divided into two areas: the top area, displays status information and methods names while the bottom area, the Failure Trace, displays the stack trace for individual methods. In the top area, the Failures tab displays only the methods that have failed while the Hierarchy tab displays all of the methods in a tree view with their status to the left of the method name. When the test completes the progress bar at the top of the Test Runner should be a lovely shade of green (Fig. 5). Select Run->Run As->2 JUnit Test or press control-F11 (a keyboard shortcut which reruns the last test) to run the test again.

Figure 5. MyClassTest has passed all of its tests.
Add another method to MyClassTest:
public void
testMyMethodAgain()
{
MyClass myClass = new
MyClass();
int result =
myClass.myMethod(1);
assertTrue("result
!= 0", result == 1);
}
In testMyMethodAgain() we pass the value 1 into myMethod() and we change the expression in assertTrue() to check for a value of 1 as the result. Run the test again (Run->Run As->2 JUnit Test or press control-F11). This time the progress bar is a bright red and the Failures tab lists testMyMethodAgain() as the failing method. The Failure Trace window (directly below the Failures tab) lists the stack trace from the AssertionFailedException. Our message ("result != 0") appears in the first line of the stack trace. Success! We knew myMethod() would return a zero and therefore fail the test (Fig. 6).

Figure 6. MyClassTest failed the new test.
Select the MyClass.java tab and scroll to myMethod(). Change the line
return 0;
to the name of the incoming argument (in this case the letter i):
return i;
Select MyClassTest.java. Run the test (Run->Run As->2 JUnit Test or press control-F11). Success once again! Only this time success comes in bright green.
The JUnit framework is an almost transparent extension of the Java Development Toolkit included with Eclipse. Test cases should be added as the classes to be tested are created in order to keep the tests growing in sync with the application code. The only feature missing is the generation of Ant code to automatically run our test from an Ant build script. We will show you how to do that in another of our Eclipse tutorials (or you can cheat and look at the Ant documentation for JUnit support).
Visit the JUnit site. Download the latest version of JUnit and look for additional testing frameworks like HTTPUnit, Jenerator, jWebUnit, Hansel, JFunc, JTestCase, XMLUnit, dbUnit and…the list goes on.
Visit the Eclipse site:
Carlos Valcarcel is the Chief Architect at EinTech, Inc. and has been involved in Java and distributed systems since 1996. He has done numerous presentations at domestic and international conventions. In addition to his work as an architect, developer and mentor, he has also presented Java courses for various companies including Sun and IBM. He can be reached at carlos@eintech.com.
Copyright
2003 EinTech, Inc.
Company
and product names mentioned in The One-Page Tutorialstm are
trademarks or registered trademarks of their respective companies.