Testing a data source-based application using JUnit and IBM Rational Application Developer

In typical componentized enterprise applications, there might be a need for a unit that exclusively offers services related to the database. Often, such specialized units use data sources defined in a J2EE application server (for instance, IBM® WebSphere® Application Server). Since these units reside in the context of the application servers, testing them is sometimes complex. One common way of testing them is to create a test application that uses the data source-based component, and then deploying that test application in the application server. In such cases, developing test applications may require considerable effort on your part. This article describes a technique to test data source-based components that are deployable in an application server (such as WebSphere Application Server Version 6.0.2), using JUnit on the IBM® Rational® Application Developer Version 7.0 platform. The sample component in this article is a simple Java™-based application that provides a simple user authentication service. The article is targeted at developers who are familiar with the JUnit framework, and who have working knowledge of Rational Application Developer.


Mohan K Jadhav (mohan.jadhav@in.ibm.com), Software Engineer, EMC

Author photoMohan K Jadhav is a Staff Software Engineer with IBM India Software Labs, Bangalore. He is currently working on assuring and controlling quality of Changed Data Capture (CDC) technologies of IBM, and his interests include Java™ middleware and server-side technologies.

19 February 2008

Also available in Chinese


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.

Prerequisite software

For the purposes of this article, we assume that the following software is installed and configured properly:

  1. WebSphere Application Server V6.0.2 or later (hereafter referred to as WebSphere)
  2. IBM® DB2® Enterprise Server Version 9.0 or later (hereafter referred to as DB2)
  3. Rational Application Developer V7.0 or later
  4. JUnit V3.8.1 or later (hereafter referred to as JUnit)

For more information on the above software, please see the Resources section.

Sample application

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
class diagram with use associations

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.

Preparing the application

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.

  1. Create a sample database called SAMPLEDB in DB2.
  2. Create a sample table called SAMPLEUSER with the command shown in Listing 1.
Listing 1. Creating the sample table
  1. Add the user data shown in Listing 2 in the sample table.
Listing 2. Creating the sample data

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.

Test the sample application

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:

  1. Create the sample application
  2. Create a test application client project
  3. Configure resources for the application client project
  4. Create JUnit test cases for the application
  5. Create a runtime configuration for the application client project

Creating the sample application

You do not need to create the authentication component described previously.

  1. Open Rational Application Developer and create a new Java project called SampleDataSourceApp.
  2. Create two packages called com.ibm.datasource.sample and com.ibm.datasource.sample.db under the source folder of the SampleDataSourceApp project.
  3. Create the classes User.java, SampleDataSource.java, and Authenticator.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();
      } catch(SQLException e) { e.printStackTrace(); }
    return sampleDataSource;
  public Connection getConnection() throws SQLException	{
    return dataSource.getConnection();
  1. The project should look like that shown in Figure 2.
    Figure 2. SampleDataSourceApp project
    project explorer view

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.

  1. Go to New > Project > Application client project.
  2. In the Application client module page, enter the details as shown in Figure 3.
    Figure 3. Application client module
    new application client project dialog
  3. Click Next.
  4. In the Project Facets page, keep the default values, as shown in Figure 4.
    Figure 4. Project facets
    configuration options
  5. Click Next.
  6. clear the option for Create a default main class, as shown in Figure 5.
    Figure 5. Application client module
    specify source folder
  7. 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.

  1. In the Project Explorer view, expand the SampleDataSourceAppTest project and double-click the deployment descriptor.
  2. Open the References tab as shown in the Figure 6.
    Figure 6. Application client module
    specify WebSphere bindings
  3. Click Add.
  4. Select Resource reference as shown in Figure 7.
    Figure 7. Adding resource references
    select the type of reference
  5. Click Next.
  6. 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
      reference to an external resource
  7. Click Finish.
  8. 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
    specify application server
  9. 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.

  1. 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
    package in tree view
  2. 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
    specify the class under test
  3. 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.
  4. Enter UserAuthenticationTest as the Name of the test case.
  5. 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");
  public void testNonAuthenticUser() {
	// the password for user "Mohan" is not valid
    User user = new User("Mohan","");		

The test class contains two tests: one to authenticate a valid user and another to authenticate an invalid user.

  1. Create a lib folder under SampleDataSourceAppTest, and export the SampleDataSourceApp project as a Java™ archive (JAR) file into the lib folder.
  2. Add the above JAR file to the build path of the SampleDataSourceAppTest project.
  3. Build the project.
  4. 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
    test classes to include in suite
  5. Click Finish.
  6. The application client project requires a mandatory main class that contains a standard Java main method to execute. You will now add a main method to the AllTests.java class. Add a main() method to the AllTests.java as shown in Listing 7.
Listing 7. AllTests.java
package com.ibm.datasource.sample.test;

public class AllTests {
  public static void main(String[] av) {  
  1. Now, configure the AllTests.java as the main class for the application client project. Open the deployment descriptor of the application client project again.
  2. In the Overview tab, edit the MainClass so that it points to the AllTests.java class, as shown in Figure 13.
    Figure 13. Configuring the Main Class
    Client Deployment Descriptor tab
  3. 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.

  1. Right-click the application client project and select Run As > Run.
  2. 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
    configure launch settings
  3. Click the icon in the top left of the screen to create a new configuration.
  4. Give a name to the configuration (in this case, SampleDataSource App test) as shown in Figure 15.
    Figure 15. Create, manage, and run configurations
    application tab
  5. Ensure that the Enterprise application and the Application client module fields point to the correct values.
  6. Also, ensure that the SampleDataSourceApp.jar is included in the classpath, as shown in Figure 16.
    Figure 16. Classpath for run time
    classpath tab with tree view
  7. Additionally, add the DB2 driver JARs in the classpath of the configuration.
  8. 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.

  1. Open the Servers view by selecting Window > Show View > Other > Server > Servers in the Rational Application Developer workspace.
  2. Start WebSphere by right-clicking WebSphere Application Server v6.0 in the Servers view, as shown in Figure 17.
    Figure 17. Servers view
    tab displaying status and state
  3. Now that WebSphere is started, right-click the application client project and select Run As > Run.
  4. Select the configuration that you configured in the previous section, as shown in Figure 18.
    Figure 18. Select run-time configuration
    option to type filter text
  5. Click Run to run the JUnit tests.
  6. You should see the test results in the console, as shown in Figure 19.
    Figure 19. Test results in console
    console tab

Now you know

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



Get products and technologies



developerWorks: Sign in

Required fields are indicated with an asterisk (*).

Need an IBM ID?
Forgot your IBM ID?

Forgot your password?
Change your password

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


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name

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.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

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


All information submitted is secure.

Dig deeper into Rational software on developerWorks

Zone=Rational, WebSphere
ArticleTitle=Testing a data source-based application using JUnit and IBM Rational Application Developer