More often than not, componentized applications use a few components that use the resources in the server and run in the server context. For instance, a set of Java classes might use a data source for a popular RDBMS (relational database management system) configured in the application server. These Java objects, thus, use the data source in the server context at run time.
Testing components that use server resources is a bit challenging, because the components reside in the server context. You can test such a component at the unit level in one of the following ways:
- Unit-test the component against the local resource. For instance, supposing that the component uses a RDBMS data source configured in the application server, testing the component might involve configuring it for a local RDBMS or any other file system. Though this approach helps if you only want to quickly test the component without much dependence on the server resources, it has a disadvantage because it does not really reflect the real-time environment in which the component resides.
- Unit-test the component by creating a wrapper application over the test component and deploying the wrapper along with the component in the server. The disadvantage of this approach, however, is that developing a wrapper test application might consume considerable effort.
- Unit-test the component by running the test code in the same context as the component. For instance, run the test code in the server context itself, where the component will be running.
This article describes the last approach. It describes how to test a data source based components that are deployable in an application server using JUnit and the Rational Application Developer platform.
For the purposes of this article, we assume that the following software is installed and configured properly:
- WebSphere Application Server V6.0.2 or later (hereafter referred to as WebSphere)
- IBM® DB2® Enterprise Server Version 9.0 or later (hereafter referred to as DB2)
- Rational Application Developer V7.0 or later
- JUnit V3.8.1 or later (hereafter referred to as JUnit)
For more information on the above software, please see the Resources section.
To make the concepts in this article more relevant and easy to comprehend, it uses the following sample application that uses DB2 to store and retrieve its data.
Suppose that the application authenticates a user given a user name and password. Also assume that a list of user names and passwords are preloaded into the database, and that the application verifies against this data every time a user attempts to log in to the application.
Now, in this scenario, the authentication component shall take the user name and password as inputs, verifies against the data in the database, and returns an appropriate message about the authenticity of the user. The authentication component thus might use these components (as shown in Figure 1):
- A User class that abstracts the user in the application
- A DataSource class that provides the communication between the database and the application
- An Authenticator class that actually verifies the given user against the database
Figure 1. Class diagram for sample authentication component
After you create the sample application, you will create an application client project that contains the JUnit test cases for the sample application. This client project will be hosted in the server, where the test cases are executed.
The following sections will describe in detail how to test this sample component.
Before you create the sample application with the authentication component and the test application client, create the necessary database objects and data in the database, and also configure the data source in WebSphere.
Creating the required database objects and data
You will now create a sample database and a sample table that contains the user data.
- Create a sample database called SAMPLEDB in DB2.
- Create a sample table called SAMPLEUSER with the command shown in Listing 1.
Listing 1. Creating the sample table
CONNECT TO SAMPLEDB;
CREATE TABLE SAMPLEUSER (
USERNAME VARCHAR (50) NOT NULL,
PASSWORD VARCHAR (20) NOT NULL
);
CONNECT RESET;
|
- Add the user data shown in Listing 2 in the sample table.
Listing 2. Creating the sample data
CONNECT TO SAMPLEDB;
INSERT INTO SAMPLEUSER (USERNAME, PASSWORD) VALUES ('Mohan','mohan');
|
Configuring a data source for DB2 in WebSphere Application Server
To configure a data source in WebSphere for the sample database in DB2, please see the WebSphere InfoCenter.
For more information on data sources in WebSphere, see Resources.
Now that this article has outlined the steps and defined your sample application, you need to perform these tasks to finally test the sample application:
- Create the sample application
- Create a test application client project
- Configure resources for the application client project
- Create JUnit test cases for the application
- Create a runtime configuration for the application client project
Creating the sample application
You do not need to create the authentication component described previously.
- Open Rational Application Developer and create a new Java project called SampleDataSourceApp.
- Create two packages called com.ibm.datasource.sample and com.ibm.datasource.sample.db under the source folder of the SampleDataSourceApp project.
-
Create the classes
User.java,SampleDataSource.java, andAuthenticator.java, as shown in Listings 3 through 5.
Listing 3. User.java
package com.ibm.datasource.sample;
public class User {
private String userName;
private String password;
public User() {}
public User(String name, String pwd) {
userName = name;
password = pwd;
}
public String getUserName() { return userName; }
public String getPassword() { return password; }
public void setUserName(String userName) { this.userName = userName; }
public void setPassword(String password) { this.password = password; }
}
|
Listing 4. Authenticator.java
package com.ibm.datasource.sample;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import com.ibm.datasource.sample.db.SampleDataSource;
public class Authenticator {
public static boolean isAuthentic(User user) {
boolean authentic = false;
try {
SampleDataSource sampleDataSource = SampleDataSource.getDataSource();
Connection connection = sampleDataSource.getConnection();
Statement statement = connection.createStatement();
String sql = "SELECT count(*) AS count FROM SAMPLEUSER WHERE username='"
+ user.getUserName() + "' and password='" + user.getPassword() + "'";
ResultSet resultSet = statement.executeQuery(sql);
if(resultSet != null) {
if(resultSet.next()) {
int count = resultSet.getInt("count");
if(count > 0) { authentic = true; }
}
}
} catch(Exception e) { e.printStackTrace(); }
return authentic;
}
}
|
Listing 5. SampleDataSource.java
package com.ibm.datasource.sample.db;
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class SampleDataSource {
public static final String resourceRefName="jdbc/SampleDataSource";
private static SampleDataSource sampleDataSource = null;
private DataSource dataSource = null;
protected SampleDataSource() {}
private void setupDataSource() throws SQLException {
try {
InitialContext ctx = new InitialContext();
dataSource = (DataSource)ctx.lookup(resourceRefName);
} catch(NamingException e) { e.printStackTrace(); }
}
public static synchronized SampleDataSource getDataSource() throws SQLException {
if(sampleDataSource == null) {
try {
sampleDataSource = new SampleDataSource();
sampleDataSource.setupDataSource();
} catch(SQLException e) { e.printStackTrace(); }
}
return sampleDataSource;
}
public Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
}
|
-
The project should look like that shown in Figure 2.
Figure 2. SampleDataSourceApp project
Creating the application client project
In the previous section, you created your authentication component, wherein the isAuthentic() method in the Authenticator class takes in an instance of the User class and verifies the user data against the database.
The authentication code is now ready, so you will create the test client project in this section.
- Go to New > Project > Application client project.
-
In the Application client module page, enter the details as shown in Figure 3.
Figure 3. Application client module
- Click Next.
-
In the Project Facets page, keep the default values, as shown in Figure 4.
Figure 4. Project facets
- Click Next.
-
clear the option for Create a default main class, as shown in Figure 5.
Figure 5. Application client module
- Click Finish.
Configuring the resources for the application client project
You have created your sample application and an application client project that you will use to test the sample application.
In this section, you will configure the required resources for the application client project so that it can contain the server resources.
- In the Project Explorer view, expand the SampleDataSourceAppTest project and double-click the deployment descriptor.
-
Open the References tab as shown in the Figure 6.
Figure 6. Application client module
- Click Add.
-
Select Resource reference as shown in Figure 7.
Figure 7. Adding resource references
- Click Next.
- Fill in the data as follows (Figure 8):
-
Name:
SampleDataSource - Type: javax.sql.DataSource
- Authentication: Container
- Sharing scope: Shareable
-
Description:
Sample data source
Figure 8. Resource reference
- Click Finish.
-
In the JAAS login information section, select Use default method. In addition, give the authentication alias the same name as the alias that you created when you defined the datasource in WebSphere (as shown in Figure 9).
Figure 9. Setting authentication entries
- Save the deployment descriptor.
Creating the JUnit test cases for the application
In this section, we will add JUnit test cases for the sample application.
-
Create a package com.ibm.datasource.sample.test under the appClientModule folder, as shown in Figure 10.
Figure 10. Creating a package for JUnit tests
-
Right-click the package and select New > Other > JUnit Test Case. You will see the screen shown in Figure 11.
Figure 11. JUnit test case
- At the bottom of the dialog shown in Figure 11, the wizard asks you to add the JUnit libraries by clicking the Click here link. Click to add the JUnit libraries to the application client project.
-
Enter
UserAuthenticationTestas the Name of the test case. - Add the code shown in Listing 6 to the test class.
Listing 6. UserAuthenticationTest
package com.ibm.datasource.sample.test;
import com.ibm.datasource.sample.Authenticator;
import com.ibm.datasource.sample.User;
import junit.framework.TestCase;
public class UserAuthenticationTest extends TestCase {
public void testAuthenticUser() {
User user = new User("Mohan","mohan");
assertTrue(Authenticator.isAuthentic(user));
}
public void testNonAuthenticUser() {
// the password for user "Mohan" is not valid
User user = new User("Mohan","");
assertFalse(Authenticator.isAuthentic(user));
}
}
|
The test class contains two tests: one to authenticate a valid user and another to authenticate an invalid user.
- Create a lib folder under SampleDataSourceAppTest, and export the SampleDataSourceApp project as a Java™ archive (JAR) file into the lib folder.
- Add the above JAR file to the build path of the SampleDataSourceAppTest project.
- Build the project.
-
Now you will create a test suite for the tests. Right-click the com.ibm.datasource.sample.test package and select New > Other > JUnit Test Suite. You will see the dialog shown in Figure 12.
Figure 12. JUnit test suite
- Click Finish.
-
The application client project requires a mandatory
mainclass that contains a standard Javamainmethod to execute. You will now add amainmethod to theAllTests.javaclass. Add amain()method to theAllTests.javaas shown in Listing 7.
Listing 7. AllTests.java
package com.ibm.datasource.sample.test;
public class AllTests {
public static void main(String[] av) {
junit.textui.TestRunner.run(UserAuthenticationTest.class);
}
}
|
-
Now, configure the
AllTests.javaas themainclass for the application client project. Open the deployment descriptor of the application client project again. -
In the Overview tab, edit the Main
Class so that it points to the
AllTests.javaclass, as shown in Figure 13.
Figure 13. Configuring the Main Class
- Save the deployment descriptor.
Creating the runtime configuration for the application client
In the previous sections, you created the sample application and a test application client project in Rational Application Developer. You also created two JUnit tests in a test case, and added the server resources to the test application client project.
In this section, you will configure the test application client project for run time. Typically, in this task, you will add any JAR files, binaries, and other resources that are required by the test application client during its run time.
- Right-click the application client project and select Run As > Run.
-
Since you created the application client project with WebSphere Application Server V6.0 as the target, select WebSphere v6.0 App Client on the left pane, as shown in Figure 14.
Figure 14. New runtime configuration
- Click the icon in the top left of the screen to create a new configuration.
-
Give a name to the configuration (in this case,
SampleDataSource App test) as shown in Figure 15.
Figure 15. Create, manage, and run configurations
- Ensure that the Enterprise application and the Application client module fields point to the correct values.
-
Also, ensure that the SampleDataSourceApp.jar is included in the classpath, as shown in Figure 16.
Figure 16. Classpath for run time
- Additionally, add the DB2 driver JARs in the classpath of the configuration.
- Click Apply to save the settings for the configuration.
In the next section, you will actually run the tests.
Running the JUnit test cases to test the sample application
Now that you have completed the entire configuration required for the test application client project, you will run the client so that it will run all the JUnit tests for you.
- Open the Servers view by selecting Window > Show View > Other > Server > Servers in the Rational Application Developer workspace.
-
Start WebSphere by right-clicking WebSphere Application Server v6.0 in the Servers view, as shown in Figure 17.
Figure 17. Servers view
- Now that WebSphere is started, right-click the application client project and select Run As > Run.
-
Select the configuration that you configured in the previous section, as shown in Figure 18.
Figure 18. Select run-time configuration
- Click Run to run the JUnit tests.
-
You should see the test results in the console, as shown in Figure 19.
Figure 19. Test results in console
In this article, you have learned how to:
- Create a test application client project in Rational Application Developer to test the application
- Configure the above test project to use server resources
- Add JUnit tests to the test project
- Run the JUnit tests to test the sample application
Learn
-
For more information on WebSphere v6.0, see Information Center.
-
For more information on using data sources in WebSphere Application Server, see http://publib.boulder.ibm.com/infocenter/wasinfo/v6r0/index.jsp.
- Visit the
Rational Application Developer and
WebSphere Application Server areas on developerWorks,
and get the resources you need to advance your skills with these tools.
- Browse the
technology bookstore
for books on these and other technical topics.
- To learn more, consider Web-based training courses on
Rational Application Developer and
WebSphere Application Server.
- Subscribe to the
developerWorks Rational zone newsletter.
Keep up with developerWorks Rational content. Every other week, you'll
receive updates on the latest technical resources and best practices for the
Rational Software Delivery Platform.
- Subscribe to the
Rational Edge newsletter
for articles on the concepts behind effective software development.
Get products and technologies
- Download
IBM product evaluation versions
and get your hands on application development tools and middleware products from
DB2®,Rational® and WebSphere®.
- See
JUnit.org
to get the latest JUnit resources.
- Download
trial versions of IBM Rational software.
- Download a free trial version of Rational Application Developer.
Discuss
- Check out
developerWorks
blogs and
get involved in the
developerWorks community.
-
Check out Rational Software Architect, Rational Data Architect, Rational Software Modeler, Rational Systems Developer, Rational Application Developer, and Rational Web Developer forum: Ask questions about Rational Application Developer.
Comments (Undergoing maintenance)






