Skip to main content

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

All information submitted is secure.

  • Close [x]

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

  • Close [x]

Rational Application Development certification prep, Part 6: Debugging and testing Java applications

Matthew Stobo (mstobo@us.ibm.com), IBM Senior IT Specialist, IBM
Matthew Stobo is a Senior IT Specialist for the IGS Sales Team--East supporting WebSphere Application Server. Previously he was a Senior Instructor with IBM IT Education Services, where he developed and taught courses across the Java and WebSphere curricula. He regularly trained employees of Fortune 500 companies, large banks, and various government agencies in the fundamentals of J2EE development using Rational Application Developer and the administration of WebSphere Application Server. He received his Masters of Information Technology Education from Dalhousie University.

Summary:  In this sixth in a series of seven tutorials created to help you prepare for the IBM Certification Test 255, Developing with IBM Rational Application Developer for WebSphere Software V6, learn how to debug and test components of a J2EE application using the Integrated Test Environment of Rational Application Developer and its built-in support for JUnit. Using breakpoints and other features of the Debug Perspective, step through Java code to find possible code breakers. Finish by mastering the art of creating JUnit TestCases and TestSuites and running them inside the development environment.

View more content in this series

Date:  11 Apr 2006
Level:  Intermediate PDF:  A4 and Letter (3398 KB | 65 pages)Get Adobe® Reader®

Activity:  8126 views
Comments:  

Performing unit testing with JUnit

The final section of this tutorial introduces you to Application Developer's built-in support for JUnit. This tutorial does not teach a testing methodology, nor does it teach all of the capabilities of JUnit. Rather, it shows how Application Developer supports JUnit. Still, we must talk a little about JUnit for those who know nothing about it.

JUnit is a regression testing framework written by Erich Gamma and Kent Beck. It is used by the developer who implements unit tests in Java. JUnit is open source software, released under the Common Public License Version 1.0 and hosted on SourceForge. (See Resources for links to sites on JUnit and Common Public License.)

The fundamental part of JUnit is a TestCase. Build TestCases to run tests against individual classes. Those TestCases can then be run together in a TestSuite. All of these tests can be versioned with your source code to provide a mechanism for regression testing.

Let's see the support that Application Developer has for JUnit.

  1. To use JUnit, first select the class for which you want to build the test case. In this case select the NameHandler.java file in the Project Explorer. Go to the File menu and select File > New > Other.
  2. When the window opens select Java > JUnit > JUnit Test Case.
  3. If you do not see the JUnit folder, select the Show All Wizards check box.

    Figure 47. New wizard selection window
    New wizard selection window
  4. Click Next.
  5. Application Developer then verifies if JUnit is on your projects class path. If it is not, the following window opens:

    Figure 48. Classpath verifier
    Classpath verifier
  6. Click Yes to add the junit.jar to you build path.
  7. By first selecting the NameHandler.java file in the Project Explorer, the wizard is pretty much filled out for you when it opens. If yours is not, fill in the fields to match the following image:

    Figure 49. New JUnit test case wizard
    New JUnit test case wizard
  8. You have to check the check boxes in either case. After you have filled in this screen, click Next.
  9. You are now presented with a screen that allows you to create the Test methods for your TestCase. Any methods that you check here are added to your class and prefaced with test (for example, testProcessName). The JUnit runtime then uses reflection to search for any methods that begin with test... and runs them serially. The setUp method is run before each and every test... method and the tearDown is run after each and every test... method to make sure that no residual effects from a previous test affect the next one.
  10. Check the check box next to the processName(String) method.

    Figure 50. Test methods view of wizard
    Test methods view of wizard
  11. Click Finish.
  12. Once the wizard has completed, open an editor on the NameHandlerTest.java file. The methods have already been stubbed out for you based on your input to the wizard. Edit the methods of the class to make them look like the following code. Comments have been added in the listing below to describe what the code is doing. It is not necessary to put them in your code.
    public class NameHandlerTest extends TestCase {
       /*In JUnit speak, instance variables are referred to as the fixture.
        They are usually initialized and reset by the setUp and tearDown
        methods, respectively.*/
    
       String testName = null;
    	
    public static void main(String[] args) {
       /*The main method is not used in our case.  It could be used if you
        wanted to run JUnit from the command line instead of through
        the GUI*/
    
       junit.textui.TestRunner.run(NameHandlerTest.class);
        }
        protected void setUp() throws Exception {
       /*The setUp method is used to initialize the fixture.
         It is run before each test...  method.*/
            super.setUp();
            testName = "default";
        }
        protected void tearDown() throws Exception {
       /*The teardown method is used to reset the fixture and
         prevent residual effects from previous tests.  It is
         run after each test... method.*/
    
            super.tearDown();
            testName = null;
        }
    	public void testProcessName() {
       /*The test... method uses an assertion to test for some "truth."
         In this case, it is checking to see if the expected value "true" 
         matches the actual value that is returned from the second argument.*/
    
          assertEquals(true, NameHandler.processName(testName).
    	    contains(testName.toUpperCase()));
    	}
    }
    

  13. Save the changes to your code. Now select the NameHandlerTest.java file in the Project Explorer. Open a context menu and choose Run > JUnit Test. Application Developer now uses the JUnit runtime to execute your test case. It also adds a new view to your perspective called the JUnit view. Change to this view to see the results of your test. The GUI for JUnit gives immediate feedback on your tests. You do not have to interpret the test results yourself: If the bar is green, the code is clean (This statement is made with apologies to the late Johnnie Cochran!). Okay, your code may not be clean, but it at least passed your test. You have to make sure you write quality tests to make sure that your code is clean.

    Figure 51. JUnit view
    JUnit view
  14. Make a slight change to the assertion in the testProcessName method of the NameHandlerTest class. Change the word true to false and rerun your test. The bar should now be red. In the failure trace it also reports why the test failed, listing what was expected versus what was actually returned.

    Figure 52. Hierarchy screen of JUnit view
    Hierarchy screen of JUnit view

Normally, you would create a series of test methods for this class within the same TestCase; however, you are going to do something different here to illustrate how to create and run a TestSuite. A TestSuite is a holder for many different TestCases. Add different TestCases to the suite and then run them together as a group instead of individually. To create your TestSuite you need a couple of TestCases; you already have one. Let's create another! For illustrative purposes, the easiest way to do this is to make a copy of your previous TestCase and edit it.

  1. Open a context menu on NameHandlerTest.java.
  2. Choose Copy from the menu. Now, paste it back into the same package. When you do a Name Conflict window opens! Use it to enter the name for your new TestCase: NameHandlerTestforNull.

    Figure 53. Name conflict dialog
    Name conflict dialog
  3. Open a java editor on your new TestCase and make the following change to the testProcessName() method:
    public void testProcessName() {
    		NameHandler.processName(testName);
    		assertNotNull(NameHandler.nameSet);
    }
    

To create the TestSuite, use the File menu to open a wizard.

  1. Choose File > New > Other.
  2. Select Java > JUnit > JUnit Test Suite.

    Figure 54. Select a wizard view
    Select a wizard view
  3. Click Next.
  4. Edit your dialog to match the following screen. Be sure to check both TestCases, as this is how to add them to the TestSuite. Optionally check the check box to create a main() method. Remember that this is only used if you want to access your test from the command line. Namely, it provides a way to script your tests through frameworks such as ANT.

    Figure 55. New JUnit test suite wizard
    New JUnit test suite wizard
  5. Click Finish.

Now you are ready to test your suite. Use the exact same steps you used for running an individual test -- by running the TestSuite as a JUnit test. Do so now! You see the results from the two TestCases listed in the JUnit view. If you left the value in the testProcessName method set to false you have failed one, or both of your tests. Change the value back to true to pass.


Figure 56. JUnit view for TestSuite
JUnit view for TestSuite

9 of 13 | Previous | Next

Comments



Help: Update or add to My dW interests

What's this?

This little timesaver lets you update your My developerWorks profile with just one click! The general subject of this content (AIX and UNIX, Information Management, Lotus, Rational, Tivoli, WebSphere, Java, Linux, Open source, SOA and Web services, Web development, or XML) will be added to the interests section of your profile, if it's not there already. You only need to be logged in to My developerWorks.

And what's the point of adding your interests to your profile? That's how you find other users with the same interests as yours, and see what they're reading and contributing to the community. Your interests also help us recommend relevant developerWorks content to you.

View your My developerWorks profile

Return from help

Help: Remove from My dW interests

What's this?

Removing this interest does not alter your profile, but rather removes this piece of content from a list of all content for which you've indicated interest. In a future enhancement to My developerWorks, you'll be able to see a record of that content.

View your My developerWorks profile

Return from help

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Rational
ArticleID=107590
TutorialTitle=Rational Application Development certification prep, Part 6: Debugging and testing Java applications
publish-date=04112006
author1-email=mstobo@us.ibm.com
author1-email-cc=

Tags

Help
Use the search field to find all types of content in My developerWorks with that tag.

Use the slider bar to see more or fewer tags.

Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere).

My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).

Use the search field to find all types of content in My developerWorks with that tag. Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere). My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).

Try IBM PureSystems. No charge.