get started with unit and component testing using ibm ... · there are four main testing types, or...

53
Get started with unit and component testing using IBM Rational tools A comprehensive guide for unit and component testing Skill Level: Intermediate Rosaline Makar ([email protected]) Software Engineer IBM 11 Oct 2007 Component testing is essential for the integration of code that enables crucial application functionality. This tutorial takes you step by step through unit and component testing specifically for Java™ code, Web services, servlets, Service Component Architecture (SCA), and Enterprise JavaBeans (EJB) beans using the JUnit and Jakarta Cactus testing frameworks and simple HelloWorld samples. Also, learn how to automate these tests using IBM® Rational® Software Architect, IBM Rational Application Developer, and IBM WebSphere® Integration Developer. Section 1. Before you start About this tutorial This tutorial covers unit and component testing for Java code, Web services, servlets, SCA, and EJB beans through HelloWorld samples (developing a HelloWorld program is considered the easiest way to learn new concepts). Here you perform unit and component testing using the JUnit and Jakarta Cactus testing frameworks. Objectives Upon completion of this tutorial, you should understand how to perform unit and component testing, and automate those tests with Apache Ant using IBM Rational Get started with unit and component testing using IBM Rational tools © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 1 of 53

Upload: phamdat

Post on 22-May-2018

224 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

Get started with unit and component testing usingIBM Rational toolsA comprehensive guide for unit and component testing

Skill Level: Intermediate

Rosaline Makar ([email protected])Software EngineerIBM

11 Oct 2007

Component testing is essential for the integration of code that enables crucialapplication functionality. This tutorial takes you step by step through unit andcomponent testing specifically for Java™ code, Web services, servlets, ServiceComponent Architecture (SCA), and Enterprise JavaBeans (EJB) beans using theJUnit and Jakarta Cactus testing frameworks and simple HelloWorld samples. Also,learn how to automate these tests using IBM® Rational® Software Architect, IBMRational Application Developer, and IBM WebSphere® Integration Developer.

Section 1. Before you start

About this tutorial

This tutorial covers unit and component testing for Java code, Web services,servlets, SCA, and EJB beans through HelloWorld samples (developing aHelloWorld program is considered the easiest way to learn new concepts). Here youperform unit and component testing using the JUnit and Jakarta Cactus testingframeworks.

Objectives

Upon completion of this tutorial, you should understand how to perform unit andcomponent testing, and automate those tests with Apache Ant using IBM Rational

Get started with unit and component testing using IBM Rational tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 1 of 53

Page 2: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

Application Developer, IBM Rational Software Developer, or IBM WebSphereIntegration Developer.

Prerequisites

To follow along with this tutorial, you should have a basic knowledge of thetechnology you want to test, whether it's SCA, servlets, EJB beans, Web services, orJava code. You should also have basic technical experience with the products listedin the System requirements section.

System requirements

Related content

• Download a free trial version of Rational SoftwareArchitect V6.0

• Rational Application Development certification prepseries

• In pursuit of code quality series

• Tech briefing: Effective software testing

In this tutorial, you can use any of the following tools to test Java code, Webservices, servlets, and EJB beans:

• Rational Software Architect V6.0

• Rational Application Developer V6.0

To perform SCA testing along with Java, Web services, servlets, and EJB testing,you need WebSphere Integration Developer V6.0.1 or 6.0.2.

Running component testing requires IBM Rational Agent Controller, which is anadd-on included in the Rational Software Architect bundle.

Section 2. Introduction

Testing is crucial in any software development project. It simulates several executionpaths to deliver a bug-free and well-tested product that ensures its robustness andhigh quality for the customer. Neglecting software testing—because of tight deliverydates, planning to rely on release fixes, or other reasons—increases the costs offixing bugs that appear later. This is because bug fix costs increase drastically as thesoftware development cycle continues.

developerWorks® ibm.com/developerWorks

Get started with unit and component testing using IBM Rational toolsPage 2 of 53 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 3: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

There are four main testing types, or phases, performed within the softwaredevelopment cycle, as shown in Figure 1:

1. Unit testing is white-box testing used to test basic units of code,including Java classes, Web services, EJB beans, and servlets.

2. Component testing tests the integration of basic units of code to performcertain functions before they are integrated into the production code base.

3. System testing tests the overall system and ensures that a group ofcomponents are integrated together.

4. Acceptance testing tests whether the software product meets thecustomer's functional and nonfunctional requirements.

Figure 1. Software testing

Note the pyramid-like structure, which emphasizes the importance of the testingsequence. For instance, after performing unit testing on each unit of code, youexecute component testing to ensure the validity of the integration of these units ofcode.

JUnit is a regression testing framework for Java written by Erich Gamma and KentBeck. As described on the Apache Web site, Cactus is a simple testing frameworkfor unit testing server-side Java code (such as servlets, EJB beans, tag libraries, andfilters). Cactus, which extends JUnit, is designed to lower the cost of writing tests forserver-side code, and it implements an in-container strategy, which means that testsare executed inside the container server (see Resources for a link to moreinformation about Cactus). Throughout this tutorial, you use the JUnit and Cactustesting frameworks to demonstrate unit and component testing. All the testsillustrated in this tutorial are available in the Download section at the end of thistutorial.

ibm.com/developerWorks developerWorks®

Get started with unit and component testing using IBM Rational tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 3 of 53

Page 4: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

Section 3. Prepare your testing environment

This section introduces the environment preparations needed throughout thistutorial.

Enable capabilities

If you're using either Rational Software Architect, Rational Application Developer, orWebSphere Integration Developer, you need to enable Web service developmentand testing capabilities:

1. Select Window > Preferences > Workbench > Capabilities.

2. Check Web Service Developer in the right pane, as shown in Figure 2.

Figure 2. Enabling capabilities

developerWorks® ibm.com/developerWorks

Get started with unit and component testing using IBM Rational toolsPage 4 of 53 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 5: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

JUnit testing preparation

The project that uses JUnit framework for testing must include junit.jar in its classpath, which exists in <IDE_HOME>\eclipse\plugins\org.junit_3.8.1\junit.jar.<IDE_HOME> is the Rational Application Developer, Rational Software Developer,or WebSphere Integration Developer installation directory. For example, if you'reusing WebSphere Integration Developer, and its installation directory is atC:\Program Files\IBM\WebSphere\601, then junit.jar should be in C:\ProgramFiles\IBM\WebSphere\601\eclipse\plugins\org.junit_3.8.1. To add junit.jar to theproject class path:

1. Right-click the project, and select Properties.

2. Choose Java Build Path from the left pane.

ibm.com/developerWorks developerWorks®

Get started with unit and component testing using IBM Rational tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 5 of 53

Page 6: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

3. Go to the Libraries tab, and click Add External JARs.

4. Browse to junit.jar, as shown in Figure 3.

Figure 3. Adding junit.jar to class path

Cactus testing preparation

To use the Cactus framework for server-side unit testing in a dynamic Web project,you must follow these steps:

1. Add the following .jar files to WebContent\WEB-INF\lib:

• aspectjrt-1.2.1.jar

• cactus-1.7.2.jar

• commons-httpclient-2.0.2.jar

• commons-logging-1.0.4.jar

• junit.jarNote: Cactus extends JUnit, hence junit.jar must be included. (TheCactus .jar files are available in the Download section or fromapache.org.)

Now you need to add Cactus servlets that are crucial for calling test methods on theserver side (through the ServletTestRedirector servlet), and add servlets thatare necessary for running tests (through ServletTestRunner servlet). To add theservlets:

1. Open the web.xml file of the dynamic Web project.

2. Click the Source tab, and add the following two servlets, as shown inListing 1:

• Servlet name: ServletRedirector, Servlet class:

developerWorks® ibm.com/developerWorks

Get started with unit and component testing using IBM Rational toolsPage 6 of 53 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 7: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

org.apache.cactus.server.ServletTestRedirector.

• Servlet name: ServletTestRunner, Servlet class:org.apache.cactus.server.runner.ServletTestRunner.

Listing 1. Adding Cactus servlets

<servlet><servlet-name>ServletRedirector</servlet-name>

<servlet-class>org.apache.cactus.server.ServletTestRedirector</servlet-class></servlet><servlet><servlet-name>ServletTestRunner</servlet-name>

<servlet-class>org.apache.cactus.server.runner.ServletTestRunner</servlet-class></servlet>

<servlet-mapping><servlet-name>ServletRedirector</servlet-name><url-pattern>/ServletRedirector</url-pattern>

</servlet-mapping><servlet-mapping><servlet-name>ServletTestRunner</servlet-name><url-pattern>/ServletTestRunner</url-pattern>

</servlet-mapping>

3. To automate Cactus test cases using Ant and to run the Cactus Ant task,add cactus-ant-1.7.2.jar and cargo-0.5.jar underWebContent\WEB-INF\lib. (These .jar files are available in the Downloadsection or from apache.org.)

Section 4. Unit testing

This section covers the following types of unit testing:

• Java and Web service unit testing using the JUnit framework

• Servlet and EJB unit testing using the Cactus framework

Java unit testing

Create a Java class under test

The following steps show the Java class to be tested:

1. Import HelloWorldJava.zip (available in the Download section) as aproject interchange, or create a Java project called HelloWorldJava.

2. Create a class named HelloWorld under the package com.ibm.tdc.

ibm.com/developerWorks developerWorks®

Get started with unit and component testing using IBM Rational tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 7 of 53

Page 8: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

3. Paste the code from Listing 2 into the HelloWorld class.Listing 2. HelloWorld Java code

package com.ibm.tdc;public class HelloWorld {

public String getGreeting (String name){

return "Hello! "+name;}

}

Create a JUnit test case

A test case is a set of test inputs, execution conditions, and expected resultsdeveloped for a particular objective. To create a JUnit test case for a certain Javaclass, follow these steps:

1. Switch to the Java perspective.

2. Right-click HelloWorld.java, and select New > JUnit Test Case.

3. A message box appears for adding junit.jar to the build path, as shown inFigure 4.Figure 4. Adding junit.jar

4. Click Yes.

5. Click JUnit Test Case, and the Test Methods dialog box appears wherethere's mapping between the options selected and the Java code that willbe generated. This comes from the New JUnit Test Case wizard, which isdisplayed in Figure 5.Figure 5. New JUnit Test Case wizard

developerWorks® ibm.com/developerWorks

Get started with unit and component testing using IBM Rational toolsPage 8 of 53 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 9: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

6. In the generated code, you can edit the test method for testing logic, asshown in Listing 3.Listing 3. HelloWorld unit test

package com.ibm.tdc;import junit.framework.TestCase;public class HelloWorldTest extends TestCase{

private HelloWorld helloWorld;public static void main(String[] args){

// TestRunner is used to execute test cases// textui is used to run test cases in text mode

junit.textui.TestRunner.run(HelloWorldTest.class);}

/** @see TestCase#setUp(), It is executed before each test method*/

protected void setUp() throws Exception{

super.setUp();helloWorld = new HelloWorld();

}

/** Tests the getGreeting method*/

public void testGetGreeting(){

// The assertion succeeds if the left argument equals to theright argument

assertEquals("Hello! Rose", helloWorld.getGreeting("Rose"));}

}

ibm.com/developerWorks developerWorks®

Get started with unit and component testing using IBM Rational tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 9 of 53

Page 10: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

In Listing 3, please note the following:

• public static void main(String[] args) is optional, butused to run the JUnit test case from the command line.

• TestRunner is used to execute test cases.

• textui is used to run test cases in text mode, hence the test resultsappear in the console.

• setUp() is one of methods of the TestCase class. It's executedbefore each test method, while tearDown() is executed after eachtest method. Both setUp() and tearDown() are optional methods.In Listing 3, setUp() is used to make a new instance of the classunder test.

• testGetGreeting() tests the getGreeting() method. JUnitnaming conventions state that test methods must have the prefixtest and take no arguments, that is, it should follow this signature—public void testXXX() [throws ...] —because JUnitTestRunner uses reflection to run test methods automatically. Theremust be at least one test method in a test case, otherwise runningJUnit test case causes a failure.

• assertEquals() is used to compare the test result and theexpected value. The assertion succeeds if the expected and theactual results are equal, and fails otherwise. JUnit provides differentversions of assertion to support various output checking. (SeeResources for a link to more information about the Assert class.)

7. The JUnit test case execution is illustrated in the sequence diagram inFigure 6.Figure 6. JUnit behavior

developerWorks® ibm.com/developerWorks

Get started with unit and component testing using IBM Rational toolsPage 10 of 53 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 11: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

Run the JUnit test case

You can run the JUnit test case using one of the following two methods:

• Right-click HelloWorldTest, and select Run > JUnit Test. A green barappears, as shown in Figure 7, indicating the success of the test case. (Ared bar indicates test-case failure or error.)Figure 7. Running the JUnit test case

ibm.com/developerWorks developerWorks®

Get started with unit and component testing using IBM Rational tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 11 of 53

Page 12: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

Failures can

occur due to:

• Failure in the assertion statement.

• The occurrence of the message, fail(String message), which isused to fail a test and may be placed inside a catch block.

• No test methods are defined within the test-case class.Errors can occur due to:

• An exception that hasn't been tested for and wasn't expected, forexample, an exception that wasn't caught, such asNullPointerException.

• Another method for running a JUnit test case is right-clickingHelloWorldTest and selecting Run > Java Application, which runs thetest case as a Java application. Note that the test results, in the case oftextui, appear on the console.Figure 8. Running the test case as a Java application

developerWorks® ibm.com/developerWorks

Get started with unit and component testing using IBM Rational toolsPage 12 of 53 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 13: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

Create a test suite

A test suite is used to collect several test cases in one suite; so with one click youcan run a number of test cases.

1. Right-click the package of the test case, com.ibm.tdc, and select New >Other > Java > JUnit > JUnit Test Suite.

2. Click Next.

3. Select the test cases you want to include in the test suite, as shown inFigure 9, and click Finish.Figure 9. Creating new test suite

ibm.com/developerWorks developerWorks®

Get started with unit and component testing using IBM Rational tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 13 of 53

Page 14: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

The following code is automatically generated:

Listing 4. The AllTests test suite

package com.ibm.tdc;import junit.framework.Test;import junit.framework.TestSuite;public class AllTests{public static void main(String[] args){

junit.textui.TestRunner.run(AllTests.suite());}public static Test suite(){

TestSuite suite = new TestSuite("Test for com.ibm.tdc");//$JUnit-BEGIN$suite.addTestSuite(HelloWorldTest.class);//$JUnit-END$return suite;

}}

developerWorks® ibm.com/developerWorks

Get started with unit and component testing using IBM Rational toolsPage 14 of 53 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 15: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

In this case, addTestSuite() is used to add the test case classes.

Running a test suite is exactly the same as running the JUnit test case. Note thatTestRunner looks for public static Test suite() to run the test suite.

Web services unit testing

What is a Web service proxy?A Web service proxy is a set of generated classes from a WebServices Description Language (WSDL) file that are used to simplifyclient development by hiding lookup and invocation details in simpleJava code.

You can test a Web service using JUnit by generating a proxy from the Web service.JUnit test cases are run against the proxy, which invokes the Web service under thehood. Successfully testing the proxy implies success in testing the Web service.

Create a Web service under test

To create a Web service under test, import HelloWebService.zip (available in theDownload section) as a project interchange. This Web service has only oneoperation— getGreeting() —which functions as the HelloWorld class in theJava project that was tested previously. Listing 5 shows the Web serviceimplementation.

Listing 5. Web service implementation

package com.yourco.www;public class HelloPortBindingImpl implements HelloPortType{

public String getGreeting(java.lang.String name) throwsjava.rmi.RemoteException

{return "Hello! "+name;

}}

Create a Web service test

The following steps walk you through creating a Java project that contains the Webservice client classes and the Web service unit test class:

1. Create a Java project named HelloWebServiceTest to represent aWeb service test project.

2. To generate the Web service client (that is, proxy classes), create a foldernamed wsdl under the HelloWebServiceTest Java project.

3. Paste the HelloService.wsdl file (retrieved from the HelloWebServiceproject) in the wsdl folder.

ibm.com/developerWorks developerWorks®

Get started with unit and component testing using IBM Rational tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 15 of 53

Page 16: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

4. Right-click HelloService.wsdl, and select Web Services > GenerateClient, as shown in Figure 10.Figure 10. Web service unit test

5. In the Web Service Client wizard, follow the defaults in the wizard, thenclick Finish. Note that Web service run time must be indicated as IBMWebSphere in the Client Environment Configuration dialog box (seeFigure 11).Figure 11. Client Environment Configuration

6. Right-click HelloPortTypeProxy.java, and select New > JUnit TestCase. It can be tested as any Java class (refer to the Create a JUnit testcase section). Note that HelloPortTypeProxy contains the Web serviceoperations.

developerWorks® ibm.com/developerWorks

Get started with unit and component testing using IBM Rational toolsPage 16 of 53 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 17: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

7. getGreeting() is the method that you test. You can complete the testcase class with the code shown in Listing 6.Listing 6. Web service unit testing

package com.yourco.www;import java.rmi.RemoteException;import junit.framework.TestCase;

public class HelloPortTypeProxyTest extends TestCase{private HelloPortTypeProxy helloPortTypeProxy;public static void main(String[] args){

junit.textui.TestRunner.run(HelloPortTypeProxyTest.class);}

protected void setUp() throws Exception{

super.setUp();helloPortTypeProxy = new HelloPortTypeProxy();

}

public void testGetGreeting() throws RemoteException{

String greeting = null;greeting = helloPortTypeProxy.getGreeting("Rosa");assertEquals("Hello! Rosa", greeting);

}}

Note: testGetGreeting() throws RemoteException becausegetGreeting() throws this exception.

Run a Web service test

Perform one of the following steps to run the Web service test, and different failureand error scenarios:

• Refer to the Run the JUnit test case section to run the test case.According to the testGetGreeting() code in Listing 6, ifHelloWebService is down (not deployed on the server for example),the JUnit framework catches the remote exception and generates an errorwith a complete stack trace for the exception—which is useful fordebugging—as shown in the Figure 12.Figure 12. Web service down error

ibm.com/developerWorks developerWorks®

Get started with unit and component testing using IBM Rational tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 17 of 53

Page 18: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

Note that in this case, the error emphasizes an unanticipated problem,which indicated that an uncaught exception (remote exception) occurred.

• Another approach is to catch the RemoteException, as shown in Listing7.Listing 7. Web service unit testing

public void testGetGreeting(){

String greeting = null;try {

greeting = helloPortTypeProxy.getGreeting("Rosa");assertEquals("Hello! Rosa", greeting);

} catch (RemoteException e) {fail("Remote Exception Occurred...");

}}

In Listing 7, the RemoteException call is anticipated, and the use of fail()doesn't generate a complete stack trace including the method that raised theexception; but it does generate the enclosed message.

If HelloWebService is down, fail() is executed and failure occurs, as shown inFigure 13.

developerWorks® ibm.com/developerWorks

Get started with unit and component testing using IBM Rational toolsPage 18 of 53 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 19: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

Figure 13. Web service down

Note that failure emphasizes that an anticipated problem occurred.

Servlet unit testing

This section explores HelloWorld servlet unit testing. You use the Cactus testingframework, which extends the JUnit testing framework to execute in-containertesting.

Create a servlet under test

The following steps walk you through creating a simple servlet and testing it.

1. Import HelloWorld.zip (available in the Download section) as a projectinterchange. Or create a dynamic Web project named HelloWorld, andcreate a servlet named HelloWorldServlet.

2. Paste the code from Listing 8 into HelloWorldServlet, which:

• Takes a name from the request parameter.

• Sets a greeting to the session.

• Writes the greeting to the response.Listing 8. HelloWorldServlet

package com.ibm.tdc;import java.io.IOException;import java.io.PrintWriter;

import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;

public class HelloWorldServlet extends HttpServlet

ibm.com/developerWorks developerWorks®

Get started with unit and component testing using IBM Rational tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 19 of 53

Page 20: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

{public void doGet(HttpServletRequest request, HttpServletResponse

response)throws IOException{

PrintWriter pw = response.getWriter();response.setContentType("text/html");getGreeting(request);pw.print("<html><head/><body><h1>" +request.getSession().getAttribute("greeting") +

"</h1></body></html>");}

public String getGreeting(HttpServletRequest request){

String name = request.getParameter("name");request.getSession().setAttribute("greeting", "Hello

"+name+"!");return name;

}}

If you tested this servlet on the browser by writinghttp://localhost:9080/HelloWorld/HelloWorldServlet?name=rosa,the result should look like Figure 14.

Figure 14. Running the servlet

Create a servlet test

Follow these steps to create the HelloWorldServletTest class, which extendsthe Cactus ServletTestCase class and lets you test HelloWorldServlet.

1. Perform the steps mentioned in the Cactus testing preparation section.

2. Switch to the Java perspective.

3. Right-click HelloWorldServlet.java, and select New > Other > Java >JUnit > JUnit Test Case.

4. In the JUnit Test Case dialog box, choose

developerWorks® ibm.com/developerWorks

Get started with unit and component testing using IBM Rational toolsPage 20 of 53 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 21: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

org.apache.cactus.ServletTestCase as the superclass, then clickNext.

5. Choose the getGreeting method, and click Finish, as shown in Figure15.Figure 15. Selecting the method to be tested

6. Set the request name parameter from the client side usingbeginGetGreeting, as shown in Listing 9.Listing 9. beginGetGreeting

public void beginGetGreeting(WebRequest webRequest){

webRequest.addParameter("name", "Rose");}

Note that the following actions occur:

• beginXXX() is executed on the client side before testXXX() on theserver side.

ibm.com/developerWorks developerWorks®

Get started with unit and component testing using IBM Rational tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 21 of 53

Page 22: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

• endXXX() is executed at the end of a test at the client side.

• setUp() and tearDown() are executed on the server side beforeand after testXXX(), respectively.

• WebRequest contains HTTP request data for a Cactus test case.

7. Add the code shown in Listing 10 to the body of testGetGreeting.Listing 10. testGetGreeting

HelloWorldServlet helloWorldServlet=new HelloWorldServlet();helloWorldServlet.getGreeting(request);assertEquals("Hello Rose!",session.getAttribute("greeting"));

The code in Listing 10:

• Constructs a new object of HelloWorldServlet.

• Calls getGreeting() and passes request to it, which is one of theimplicit objects initialized automatically by Cactus. request is of thetypeorg.apache.cactus.server.HttpServletRequestWrapper,which it inherits fromjavax.servlet.http.HttpServletRequest. Hence, it can bepassed to the servlet method that takes a variable of typeHttpServletRequest.

• Checks the equality of the expected value and the value stored in thesession attribute.

The overall code should look like what's shown in Listing 11.

Listing 11. HelloWorldServletTest

package com.ibm.tdc;import org.apache.cactus.ServletTestCase;import org.apache.cactus.WebRequest;public class HelloWorldServletTest extends ServletTestCase{

public void beginGetGreeting(WebRequest webRequest){

webRequest.addParameter("name", "Rose");}

public void testGetGreeting(){

HelloWorldServlet helloWorldServlet=new HelloWorldServlet();helloWorldServlet.getGreeting(request);assertEquals("Hello Rose!",session.getAttribute("greeting"));

}}

Run the servlet test

The following steps show how to run the HelloWorldServletTest class.

developerWorks® ibm.com/developerWorks

Get started with unit and component testing using IBM Rational toolsPage 22 of 53 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 23: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

1. Right-click the HelloWorldServletTest test class, and select Run >Run.

2. Select JUnit in the Configurations list, and click New.

3. Click the Arguments tab in the right pane.

4. Set the Cactus context URL in the VM arguments field to-Dcactus.contextURL=http://localhost:9080/HelloWorld,as shown in Figure 16. Note that HelloWorld is the project name.cactus.contextURL represents the application context under which thetest application runs.Figure 16. Cactus configuration

5. Click Run. The test should pass, and you'll see a green bar like the oneshown in Figure 7, which indicates a successful test.

EJB unit testing

This section explains how to create a HelloWorld stateless session EJB bean andhow to perform unit testing using the Cactus testing framework.

Create an EJB under test

Follow these steps to create a HelloWorld stateless session EJB bean:

1. To create the stateless session EJB bean to be tested, importHelloEJB.zip (available in the Download section) as a projectinterchange. Or select File > New > Project > EJB > EJB project, enterHelloEJB as the name of the project, then click Finish.

2. Right-click HelloEJB, select New > Other > EJB > Enterprise Bean,then click Next.

ibm.com/developerWorks developerWorks®

Get started with unit and component testing using IBM Rational tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 23 of 53

Page 24: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

3. Enter the values shown in Figure 17, where you select Session bean asthe EJB type and define the basic properties of the bean. Then click Next.Figure 17. Creating a new EJB bean

4. From the Session type drop-down list, choose Stateless, as shown inFigure 18, then click Finish.Figure 18. Filling in EJB details

developerWorks® ibm.com/developerWorks

Get started with unit and component testing using IBM Rational toolsPage 24 of 53 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 25: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

5. Paste the code from Listing 12 in HelloBean.Listing 12. EJB method implementation

public String getGreeting(String name){

System.out.println("stateless session bean ...");return "Hello! "+name;

}

6. Promote the getGreeting() method to the remote interface, as shownin Figure 19.Figure 19. Promote to the remote interface

ibm.com/developerWorks developerWorks®

Get started with unit and component testing using IBM Rational tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 25 of 53

Page 26: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

Promoting the getGreeting() method to the remote interface (Hello)generates the line of code shown in Listing 13 in the Hello remoteinterface.Listing 13. The remote interface generated code

public String getGreeting(String name) throwsjava.rmi.RemoteException;

The remote client calls this remote method.

Create an EJB test

The testing of HelloEJB occurs in the HelloWorld dynamic Web project that youpreviously created in the Servlet unit testing section.

1. Open the deployment descriptor of HelloWorldEAR.

developerWorks® ibm.com/developerWorks

Get started with unit and component testing using IBM Rational toolsPage 26 of 53 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 27: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

2. Go to the Module tab, and add HelloEJBClient.jar to the Project UtilityJars list, as shown Figure 20.Figure 20. Project Utility JARs

3. Right-click the project HelloWorld, and select Properties > Java JARDependencies.

4. Select HelloEJBClient.jar in the right-hand list, then click OK. Figure 21shows what the JAR dependencies look like.Figure 21. JAR dependencies

ibm.com/developerWorks developerWorks®

Get started with unit and component testing using IBM Rational tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 27 of 53

Page 28: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

5. Perform the steps mentioned in the Cactus testing preparation section onthe HelloWorld Web project if you haven't already (see Create a servlettest).

6. Create a JUnit test case named HelloEJBTest for HelloEJB, and insertthe code from Listing 14 in HelloEJBTest.Listing 14. HelloEJBTest

package com.ibm.tdc;import java.util.Hashtable;import java.rmi.RemoteException;import javax.ejb.CreateException;import javax.naming.Context;import javax.naming.InitialContext;import javax.naming.NamingException;import javax.rmi.PortableRemoteObject;import org.apache.cactus.ServletTestCase;

public class HelloEJBTest extends ServletTestCase{

public void testGetGreeting() throws NamingException,RemoteException, CreateException

{Hashtable env = new Hashtable();Object obj = null;Context ctx = null;String strUrl = "iiop://localhost:2809";env.put(Context.PROVIDER_URL, strUrl);

ctx = new InitialContext(env);obj = ctx.lookup("ejb/com/ibm/tdc/HelloHome");HelloHome bfmh = (HelloHome) PortableRemoteObject.narrow(obj,

HelloHome.class);

developerWorks® ibm.com/developerWorks

Get started with unit and component testing using IBM Rational toolsPage 28 of 53 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 29: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

Hello defaultSession = bfmh.create();;assertEquals("Hello! Rosa",

defaultSession.getGreeting("Rosa"));}

}

Run an EJB under test

Refer to the Run the servlet test section to run HelloEJBTest.

Section 5. Component testing

Component testing tests the integration of basic units of code to perform certainfunctionality before they are integrated into the production code base. This sectionwalks you through using the component testing feature in WebSphere IntegrationDeveloper, Rational Software Architect, and Rational Application Developer toperform automated component testing on Java code and Web services. Theautomated component testing features extend the JUnit framework.

There are a few requirements: You need to install Rational Agent Controller beforerunning a component test. And to test Java code and Web service components, youmust first create a component test project (in either WebSphere IntegrationDeveloper, Rational Software Architect, or Rational Application Developer), whichrepresents a container for test components (see Figure 22).

Figure 22. Component testing

Create a component test project

Perform the following steps to create a component test project in which you groupthe test artifacts generated when you create a component test:

1. Import CompTest.zip (available in the Download section) as a projectinterchange. Or create a component test project by selecting File > New

ibm.com/developerWorks developerWorks®

Get started with unit and component testing using IBM Rational tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 29 of 53

Page 30: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

> Project > Component Test > Component Test Project, then clickNext, as shown in Figure 23.Figure 23. Web service component test

2. Name the component test project CompTest, and click Next.

3. Define the component test project scope (the projects to be tested insidethis component test project) by selecting the HelloWebService andHelloWorldJava projects, as shown in Figure 24.Figure 24. Test scope

developerWorks® ibm.com/developerWorks

Get started with unit and component testing using IBM Rational toolsPage 30 of 53 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 31: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

4. Click Finish.

Java component testing

Component testing is the ability to test the integration of basic units of code thathave undergone the unit testing to perform a specific functionality before they areintegrated into the production code base. Suppose that the HelloWorldJava project,which you created in the Java unit testing section, has another class calledGoodMorning. This class has one method, sayGoodMorning(), that takes astring in the format Hello! name , parses it to retrieve the name, and returnsGood Morning name . This class has passed through unit testing as theHelloWorld class. Now you want to integrate the two classes to form a certainscenario that takes name and returns Good Morning name . Here's how:

1. Select File > New > Other > Component Test > Java > JavaComponent Test, then click Next.

2. Select the CompTest component test project with which the new Java

ibm.com/developerWorks developerWorks®

Get started with unit and component testing using IBM Rational tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 31 of 53

Page 32: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

component test will be associated.

3. When the Select the components under test dialog box appears, selectthe HelloWorld and GoodMorning classes (the classes to be tested).

4. Enter HelloFlow for the test name, as shown in Figure 25, then clickNext.Figure 25. Components under test

5. To create a test based on a sequence of method calls, selectScenario-based testing, then click Next.

6. To start testing, you must first instantiate a new object from the classusing the constructor; then any sequence of methods can be called onthis object. The Define a test scenario dialog box (see Figure 26)simulates exactly this sequence of steps where you do the following:

a. To create an object of the HelloWorld class, select HelloWorld()

developerWorks® ibm.com/developerWorks

Get started with unit and component testing using IBM Rational toolsPage 32 of 53 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 33: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

from the Constructors list, then click Add.

b. To add any sequence of method calls, select and add each methodfrom the Testable Methods list in any desired sequence. In thiscase, select getGreeting(String), and click Add.

c. Select GoodMorning() from the Constructors list, and click Add.

d. Select sayGoodMorning(String), and click Add.

e. Click Finish.Figure 26. Scenario-based testing

7. Click the Test Overview tab, and click HelloFlow.java next to Behavior(see Figure 27) to view and start editing the test code.Figure 27. Test overview

ibm.com/developerWorks developerWorks®

Get started with unit and component testing using IBM Rational tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 33 of 53

Page 34: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

8. Modify the code to implement the desired tests, and click the test methodtestClassCluster() in the Java editor to show the Test Data Table.

9. Fill this table with the input data and the expected output shown in Figure28, then click Save.Figure 28. Java component test

10. From the Test Navigator, expand the CompTest component test project.

11. Right-click the HelloFlow test suite, and select Run > Component Test,

developerWorks® ibm.com/developerWorks

Get started with unit and component testing using IBM Rational toolsPage 34 of 53 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 35: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

as shown in Figure 29.Figure 29. Running component test

12. Observe the Actual column versus Expected column in the Test DataComparator view. Figure 30 shows that the test passed successfully andthat the actual and expected results match. (This is indicated by the greencolor of the results in the Actual column; if there's a mismatch betweenthe actual and the expected results, the results appear red in the Actualcolumn).Figure 30. Java test results

ibm.com/developerWorks developerWorks®

Get started with unit and component testing using IBM Rational tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 35 of 53

Page 36: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

Web services component testing

This section discusses Web services component testing by testing theHelloWebService. To create a Web service component test inside the CompTestyou created previously (in the Create a component test project section), do thefollowing:

1. Select File > New > Other > Component Test > Web Services > WebService Component Test, then click Next.

2. Select the CompTest component test project with which the new Webservice component test will be associated, then click Next.

3. In the Select the Web service under test dialog box, browse toHelloService.wsdl, then choose the port type to be tested, as shown inFigure 31. This dialog box is responsible for generating the proxy classesfrom the selected WSDL file.Figure 31. Web service under test

developerWorks® ibm.com/developerWorks

Get started with unit and component testing using IBM Rational toolsPage 36 of 53 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 37: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

4. In the Select a test pattern dialog box, select Operation-level WebService Testing to create a test for each individual operation in the classto be tested. Then click Next (see Figure 32).Figure 32. Selecting a test pattern

ibm.com/developerWorks developerWorks®

Get started with unit and component testing using IBM Rational tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 37 of 53

Page 38: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

5. Select the getGreeting(String) method (the method to be tested), thenclick Finish, as shown in Figure 33.Figure 33. Selecting a Web service method

In the Web perspective, client classes are generated, as shown in Figure34.Figure 34. Proxy classes

developerWorks® ibm.com/developerWorks

Get started with unit and component testing using IBM Rational toolsPage 38 of 53 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 39: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

6. Switch to the Test perspective, and fill the Test Data Table.Figure 35. WS component test

Note that webServiceUrlString (in the In column) is set to behttp://localhost:9080/HelloWebService/services/HelloPort, which is thevalue specified in the HelloService WSDL file inside the<soap:address> tag.

7. Right-click the project, and select Run > Test Component.

<soap:address>The <soap:address> tag content is the Web service endpoint thatrepresents the network physical address on which the Web serviceis deployed and running. (See Resources for more informationabout soap:address.)

ibm.com/developerWorks developerWorks®

Get started with unit and component testing using IBM Rational tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 39 of 53

Page 40: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

8. Observe the Actual versus Expected column in the Test Data Comparatorview. Figure 36 shows that the test passed successfully and that theactual and the expected results match. (This is indicated by the greencolor of the results in the Actual column; if there's a mismatch betweenthe actual and the expected results, the results appear red in the Actualcolumn).Figure 36. Web service test results

Section 6. Service Component Architecture testing

SCA is a new programming model designed specifically for building and assemblingbusiness solutions in a Service-Oriented Architecture (SOA) and for integrating andcomposing services. (For more information, refer to "Building SOA solutions with theService Component Architecture" [developerWorks, Oct 2005].)

You perform SCA component testing using a ServletTestCase. This test caseuses the Cactus framework to externally invoke the SCA component using astand-alone reference. In this section, you create a HelloWorldModule modulewith SCA components that are connected to a stand-alone reference. Then youcreate a dynamic Web project called HelloWorldModuleTest that tests the SCAcomponents.

Create an SCA module

Perform the following steps to create and test the SCA module:

1. Import HelloWorldModule.zip (available in the Download section) as aproject interchange. Or create a module by clicking File > New > Project> Module. Then click Next.

2. Enter HelloWorldModule as the project name.

3. In the Business Integration perspective, navigate to and right-clickHelloWorldModule > Interfaces.

developerWorks® ibm.com/developerWorks

Get started with unit and component testing using IBM Rational toolsPage 40 of 53 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 41: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

4. Select New > Interface, and name the interface HelloInterface.

5. When the Interface Editor opens, add the getGreeting operation thattakes name as input and greeting as output, as shown in Figure 37.Figure 37. HelloInterface

6. Open the Assembly Editor.

7. Drag and drop Java SCA component, name it HelloJava, and addHelloInterface to it as a component interface.

8. Drag and drop Process SCA component, name it HelloProcess, andadd HelloInterface to it as a component interface and reference.

9. Wire HelloProcess to HelloJava.

10. Double-click HelloJava (this implements it), and add the following line inthe getGreeting() operation: return "Hello! "+name;.

11. Implement HelloProcess, as shown in Figure 38.Figure 38. HelloProcess

ibm.com/developerWorks developerWorks®

Get started with unit and component testing using IBM Rational tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 41 of 53

Page 42: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

As you can see in Figure 38, Invoke is used to invoke HelloJava, andSnippet is used to change the value of the greeting.

12. Drag and drop Stand-alone References, and wire the Stand-aloneReferences to HelloJava and HelloJavaProcess, as shown in Figure39.Figure 39. HelloWorldModule

developerWorks® ibm.com/developerWorks

Get started with unit and component testing using IBM Rational toolsPage 42 of 53 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 43: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

The partner reference names shown in Figure 39 are the entry points tothe SCA components. These names are used to call the SCAcomponents during testing.

Create an SCA test

The following steps walk you through creating a dynamic Web project,HelloWorldModuleTest, that tests HelloWorldModule:

1. Switch to the J2EE perspective, and expand Enterprise Applications inthe Project Explorer view.

2. Right-click HelloWorldModuleApp, and select New > Dynamic WebProject.

3. In the New Dynamic Web Project dialog box, enter a name, such asHelloWorldModuleTest, which is the project you use to testHelloWorldModuleApp.

4. Click Finish.

5. Perform the steps covered in the Cactus testing preparation section forthe HelloWorldModuleTest project.

6. HelloWorldModuleTest—which is dependent on HelloWorldModule—mustbe added to HelloWorldModule. To do this, switch to the BusinessIntegration perspective, select HelloWorldModule, and right-click toopen the Dependency Editor.

ibm.com/developerWorks developerWorks®

Get started with unit and component testing using IBM Rational tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 43 of 53

Page 44: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

7. Expand J2EE, and click Add to add the HelloWorldModuleTest dynamicWeb project to the SCA module, as shown in Figure 40.Figure 40. Dependency Editor

8. Switch to the Web perspective, go to the Project Explorer view, andexpand HelloWorldModule > Java Resources > JavaSource.

9. Create a new class named HelloWorldTest inside the packagecom.ibm.tdc, and paste the code from Listing 15 in it.Listing 15. HelloWorldTest

package com.ibm.tdc;import org.apache.cactus.ServletTestCase;import com.ibm.websphere.sca.Service;import com.ibm.websphere.sca.ServiceManager;public class HelloWorldTest extends ServletTestCase{

public void testHelloJava(){

Serviceservice=(Service)ServiceManager.INSTANCE.locateService("HelloInterfacePartner");

String greeting = (String)service.invoke("getGreeting", "Rosa");assertEquals("Hello From First Java Component! Rosa", greeting);

}

public void testHelloProcess(){

Serviceservice=(Service)ServiceManager.INSTANCE.locateService("HelloInterfacePartner1");

String greeting = (String)service.invoke("getGreeting", "Rosa");assertEquals("Hello From Process! Rosa", greeting);

}}

The previous code tests both the HelloJava and HelloProcess SCAcomponents using the testHelloJava() and testHelloProcess()methods, respectively. Each method uses the service manager to accessthe SCA component through the partner reference name, invokes thegetGreeting() operation, then validates the result through assertion.

Run SCA module under test

developerWorks® ibm.com/developerWorks

Get started with unit and component testing using IBM Rational toolsPage 44 of 53 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 45: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

Refer to the Run the servlet test section to run HelloWorldTest.

Section 7. Test automation using Ant scripts

Ant is a Java-based tool used for build automation; in this case Ant is used toautomate JUnit and Cactus test cases, and generate the test results in XML files(see Resources for a link to more information about Ant).

JUnit Ant script

The following steps show how to use the JUnit Ant task to run the HelloWorldTest(created earlier). This lets you perform the unit test for the HelloWorld Java class,as explained in the Java unit testing section.

1. Create an XML file named build.xml, and place it in the Java project.

2. Paste the code from Listing 16 in the build.xml file.Listing 16. JUnit Ant script

<?xml version="1.0" encoding="UTF-8"?><project name="Workspace"default="junitTest"><target name="junitTest"><junit printsummary="yes"

haltonfailure="no"><classpath><pathelement location="bin" />

</classpath><formatter type="xml"/><batchtest todir="C:/temp/"><fileset

dir="C:/Workspace/HelloWorldJava"><include name="**/*Test*.java" />

</fileset></batchtest>

</junit></target></project>

In Listing 16, note that:

Ant and build automationAnt can automate your build procedure to improve productivity andquality using the built-in support of Ant for the IBM RationalSoftware Development platform. For more information, refer to"Automatically generate project builds using Ant" (developerWorks,Jan 2007).

ibm.com/developerWorks developerWorks®

Get started with unit and component testing using IBM Rational tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 45 of 53

Page 46: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

• <pathelement location="bin"/> refers to the place of the .classfiles (the classes under test and the test cases).

• <junit printsummary="yes" haltonfailure="no"> runs theJUnit test cases and prints a summary.

• <formatter type="xml"/> sets the test results format.

• <batchtest todir="C:/temp/"> specifies the location of thegenerated test results reports.

• <fileset dir="C:/Workspace/HelloWoldJava"> refers to thelocation of the Java project.

• <include name="**/*Test*.java"> refers to test case with theword Test in it under any package. Note that **/*Test*.java can bereplaced by com/ibm/tdc/HelloWorldTest.java.

3. To run Ant, drag and drop the build.xml file in the Ant view.

4. Right-click junitTest, and select Run Ant, as shown in Figure 41.Figure 41. Run Ant

5. Select the JRE tab, and choose Run in the same JRE as theworkspace (this is the JRE in which Ant will run), as shown in Figure 42.

6. Click Run.Figure 42. JRE selection

developerWorks® ibm.com/developerWorks

Get started with unit and component testing using IBM Rational toolsPage 46 of 53 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 47: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

The test results appear in the Console, and the test reports are generated at thelocation you specified earlier.

Cactus Ant script

Follow these steps to use the Cactus Ant task to run HelloWorldServletTest (createdearlier) to perform the unit test for the HelloWorldServlet servlet, as covered inthe Servlet unit testing section.

1. Add cactus-ant-1.7.2.jar and cargo-0.5.jar underWebContent\WEB-INF\lib to run the Cactus Ant task. (You can downloadthese .jar files from the Download section of this article or fromapache.org.)

2. Right-click HelloWorldEAR, select Export > EAR file, and chooseC:/temp/test/HelloWorldEAR.ear as the destination.

3. Create an XML file named build.xml, and place it in the HelloWorlddynamic Web project.

4. Paste the code from Listing 17 in the build.xml file.Listing 17. Cactus Ant script

<?xml version="1.0" encoding="UTF-8"?><project name="Workspace" default="cactusTest"><property name="server.lib"value="C:/WebSphere/ID/602/runtimes/bi_v6/lib"/><property name="project.lib" value="WebContent/WEB-INF/lib"/><path id="test.classpath"><fileset dir="${server.lib}"><include name="j2ee.jar" />

</fileset><pathelement location="WebContent/WEB-INF/classes" /></path><path id="cactus.classpath"><pathelement location="${project.lib}/cactus-1.7.2.jar"/><pathelement location="${project.lib}/cargo-0.5.jar"/><pathelement location="${project.lib}/cactus-ant-1.7.2.jar"/><pathelement location="${project.lib}/commons-httpclient-2.0.2.jar"/><pathelement location="${project.lib}/commons-logging-1.0.4.jar"/><pathelement location="${project.lib}/aspectjrt-1.2.1.jar"/>

</path><target name="cactusTest"><taskdef resource="cactus.tasks" classpathref="cactus.classpath"/><cactus printsummary="yes" haltonfailure="no"

earfile="C:/temp/test/HelloWorldEAR.ear"><classpath refid="test.classpath" />

ibm.com/developerWorks developerWorks®

Get started with unit and component testing using IBM Rational tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 47 of 53

Page 48: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

<formatter type="xml"/><batchtest todir="C:/temp/"><fileset dir="C:/Workspace/HelloWorld/JavaSource"><include name="com/ibm/tdc/HelloWorldServletTest.java" /></fileset>

</batchtest></cactus>

</target></project>

In Listing 17, note that:

• <property name="server.lib" value="..."/> refers to theplace of the server library.

• <path id="test.classpath"> refers to the j2ee.jar file.

• <path id="cactus.classpath"> refers to the Cactus .jar files.

• <taskdef resource="cactus.tasks"classpathref="cactus.classpath"/> defines the Cactus task andrefers to the Cactus .jar files.

• <cactus ... earfile="C:/temp/test/HelloWorldEAR.ear">refers to the dynamic Web project EAR file that was exported above instep 2.

5. Drag and drop build.xml in the Ant view, then right-click cactusTest >Run Ant.

6. Select the JRE tab, and choose Separate JRE.

7. Select the server on which your dynamic Web project is running. Forexample, if you're using WebSphere Process Server, choose WPSServer v6.0 JRE. (Note that the WebSphere Process Server testenvironment is available with WebSphere Integration Developer.)

8. Set the VM arguments to-Dcactus.contextURL=http://localhost:9080/HelloWorld,as shown in Figure 43.Figure 43. Separate JRE

developerWorks® ibm.com/developerWorks

Get started with unit and component testing using IBM Rational toolsPage 48 of 53 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 49: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

9. You need to add junit.jar, because it's needed by the Cactus Ant task.Select the Classpath tab, and click User Entries.

10. Click Add JARs, browse toHelloWorld\WebContent\WEB-INF\lib\junit.jar, and click OK. junit.jar isadded to the User Entries list, as shown in Figure 44.Figure 44. Adding junit.jar to User Entries

11. Click Run. The test report appears in the destination specified in the Antscript.

Section 8. Conclusion

In this tutorial, you learned how to perform unit and component testing using theJUnit and Cactus frameworks. You also walked through the automation of tests withAnt scripts using IBM Rational tools.

ibm.com/developerWorks developerWorks®

Get started with unit and component testing using IBM Rational tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 49 of 53

Page 50: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

Section 9. Acknowledgements

The author would like to thank Ahmed Abbas, Dr. Alaa Youssef, and MahmoudOuda for reviewing the tutorial and for their valuable suggestions.

developerWorks® ibm.com/developerWorks

Get started with unit and component testing using IBM Rational toolsPage 50 of 53 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 51: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

Downloads

Description Name Size Download method

Test files for this tutorial sample.zip 2.7MB HTTP

Information about download methods

ibm.com/developerWorks developerWorks®

Get started with unit and component testing using IBM Rational tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 51 of 53

Page 52: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

Resources

Learn

• Read the following IBM WebSphere Developer Technical Journals:

• "Building SOA solutions with the Service Component Architecture -- Part1" (developerWorks, Oct 2005)

• "Reliable and repeatable unit testing for Service Component Architecturemodules -- Part 1" (developerWorks, Aug 2006)

• Check out the "Rational Application Developer V6 Programming Guide," one ofmany IBM Redbooks.

• "Automatically generate project builds using Ant" (developerWorks, Jan 2007)gives you step-by-step instructions to automate your build procedure.

• Get more information about the Apache Jakarta Cactus framework.

• Learn more about the JUnit framework.

• Visit the Apache Ant Web site.

• Get more information about the Assert class.

• Get more information about the <soap:address> tag.

• The SOA and Web services zone on IBM developerWorks hosts hundreds ofinformative articles and introductory, intermediate, and advanced tutorials onhow to develop Web services applications.

• The IBM SOA Web site offers an overview of SOA and how IBM can help youget there.

• Stay current with developerWorks technical events and webcasts. Check outthe following SOA and Web services tech briefings in particular:

• Get started on SOA with WebSphere's proven, flexible entry points

• Building SOA solutions and managing the service lifecycle

• SCA/SDO: To drive the next generation of SOA

• SOA reuse and connectivity

• Browse for books on these and other technical topics at the Safari bookstore.

• Check out a quick Web services on demand demo.

Get products and technologies

• Download a free trial version of Rational Software Architect. Note: IBM RationalAgent Controller is included in the for-purchase version, not in the trial version.

• Innovate your next development project with IBM trial software, available fordownload or on DVD.

developerWorks® ibm.com/developerWorks

Get started with unit and component testing using IBM Rational toolsPage 52 of 53 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 53: Get started with unit and component testing using IBM ... · There are four main testing types, or phases, performed within the software development cycle, as shown in Figure 1: 1

Discuss

• Participate in the discussion forum for this content.

• Get involved in the developerWorks community by participating indeveloperWorks blogs, including the following SOA and Web services-relatedblogs:

• Service Oriented Architecture -- Off the Record with Sandy Carter

• Best Practices in Service-Oriented Architecture with Ali Arsanjani

• WebSphere SOA and J2EE in Practice with Bobby Woolf

• Building SOA applications with patterns with Dr. Eoin Lane

• Client Insights, Concerns and Perspectives on SOA with Kerrie Holley

• Service-Oriented Architecture and Business-Level Tooling with SimonJohnston

• SOA, ESB and Beyond with Sanjay Bose

• SOA, Innovations, Technologies, Trends...and a little fun with Mark Colan

About the author

Rosaline MakarRosaline Makar is a software engineer at IBM Egypt Cairo Technology DevelopmentCenter (C-TDC). Her current work areas include SOA and Web services. She has aB.Sc. in computer engineering and is currently preparing for a M.Sc. in computerscience.

Trademarks

IBM, the IBM logo, Rational, and WebSphere are registered trademarks of IBM in theUnited States, other countries or both.Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in theUnited States, other countries, or both.

ibm.com/developerWorks developerWorks®

Get started with unit and component testing using IBM Rational tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 53 of 53