Create test cases for Web applications

The jWebUnit framework makes testing your Web apps a breeze

Looking for a way to apply automated testing techniques to Web development? Look no further. jWebUnit, which plugs easily into most Java™ IDEs, is an open source framework for creating test cases for Web applications. Software engineer Amit Tuli introduces jWebUnit by using a sample application to describe a step-by-step approach for generating concise test cases.

Amit Tuli (amittuli@ae.ibm.com), Staff Software Engineer, IBM India Software Labs

Amit Tuli is a staff software engineer with IBM India Software Labs, Gurgaon. He is currently working on IBM Websphere Business Integration in the Solutions Group of ISL. He has five years of technical experience in Java and server-side programming on multiple platforms and has worked with relational database systems, including DB2 UDB and Oracle. He has also worked with India Research Lab on the IBM WebFountain SDK project. His areas of expertise include designing and developing stand-alone to n-tier distributed applications. He holds a master's degree in computer applications from the Guru Jambheshwar University, Hisar.



16 December 2004 (First published 31 May 2005)

Also available in Japanese

Automated testing saves you the time and effort of performing the same test steps repetitively. This article introduces jWebUnit, a set of Java classes that you can use to develop test cases for Web applications. jWebUnit is an open source project that's freely available under a BSD license. I'll show you how to download the jWebUnit libraries, configure the Eclipse platform to develop jWebUnit test cases, and build a sample test case.

Introducing jWebUnit

jWebUnit is based on HttpUnit, a Java library for the automatic testing of Web applications, and the JUnit unit-testing framework (see Resources). jWebUnit provides a high-level API for navigating a Web application, combined with a set of assertions for verifying the correctness of navigation via links, form entry and submission, table contents, and other typical business Web application features. jWebUnit comes in the form of a JAR file that's easily pluggable into most IDEs and includes other required libraries.

Testing with HttpUnit

Automated testing for Web applications means bypassing the Web browser and working with the Web site through your program. First, I'll show you how HttpUnit, one of JWebUnit's building blocks, simplifies this task. HttpUnit can emulate frames, JavaScript, page redirection cookies, and so on. When used with JUnit, HttpUnit can quickly verify a Web site's functioning.

Listing 1 shows an example test case written with HttpUnit that tries to click on the "Cookbook" link on the HttpUnit home page:

Listing 1. HttpUnit code to click on Cookbook link on HttpUnit home page
1 public class HttpUnitTest {
2  public static void main(String[] args) {
3    try {
4      WebConversation wc = new WebConversation();
5      WebRequest request = 
            new GetMethodWebRequest("http://httpunit.sourceforge.net/index.html");
6      wc.setProxyServer( "your.proxy.com", 80 );
7      WebResponse response = wc.getResponse(request);
8      WebLink httpunitLink = 
            response.getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT,"Cookbook");
9      response = httpunitLink.click();
10      System.out.println("Test successful !!");
11    } catch (Exception e) {
12      System.err.println("Exception: " + e);
13    }
14  }
15 }

The code in Listing 1 uses your.proxy.com (line 6) to connect to the Internet. If you have a direct Internet connection, you can comment this statement out. The statement in line 8 searches the page for a Web link that contains the text Cookbook. The statement in line 9 clicks on that link. If a link is found, the user sees the message Test Successful !!.

Simpler testing with jWebUnit

The test case in Listing 2 uses the jWebUnit API to perform the same task as Listing 1:

Listing 2. jWebUnit code to click on the Cookbook link on HttpUnit home page
1 public class JWebUnitTest extends WebTestCase{
2  public static void main(String[] args){
3    junit.textui.TestRunner.run(new TestSuite(JWebUnitTest.class));
4  }
5  public void setUp(){
6    getTestContext().setBaseUrl("http://httpunit.sourceforge.net");
7    getTestContext().setProxyName("webproxy.watson.ibm.com");
8    getTestContext().setProxyPort(8080);
9  }
10  public void testSearch(){
11    beginAt("/index.html");
12    clickLinkWithText("Cookbook");
13  }
14 }

If you ignore the JUnit-specific code in Listing 2, you can see that the test case is now quite neat and concise. The important lines to look at are lines 6, 11, and 12. At line 6, the base URL is set to the HttpUnit home page. Line 11 connects to the site at relative path /index.html. Line 12 clicks on the link on that page with the text Cookbook. JUnit reports success if the click works; otherwise, it reports an exception.


The jWebUnit API: A closer look

At the heart of every jWebUnit test case is net.sourceforge.jwebunit.WebTestCase class, which represents a test case. Every test case must extend from this class. (The net.sourceforge.jwebunit.WebTestCase class itself extends from junit.framework.TestCase, which represents a test case in JUnit.) Table 1 describes some of this class's commonly used methods:

Table 1. Important methods of the net.sourceforge.jwebunit.WebTestCase class
MethodDescription
public TestContext getTestContext()Gets the test case's context. You can use it to access items such as locale, base URL, and cookies.
public void beginAt(String relativeURL)Begins the conversation at URL relative to base URL.
public void setWorkingForm(String nameOrId)Begins interaction with a specified form. You don't need to call this method if the current page has only one form.
protected void submit()Submits the form -- equivalent to clicking on the form's Submit button.
public void gotoFrame(String frameName)Makes the named frame active.

Another important class is net.sourceforge.jwebunit.TestContext. It establishes the context for tests. You use this class to work with information such as cookies, session, and authorization. Table 2 shows some of this class's important methods:

Table 2. Important methods of the net.sourceforge.jwebunit.TestContext class
MethodDescription
public void addCookie(String name, String value)Adds a cookie to the test context. Added cookies are set on the WebConversation when an HttpUnitDialog is begun.
public void setResourceBundleName(String name)Sets a resource bundle to use for the test context. Used to look up expected values by key in WebTester.
public void setProxyName(String proxyName)Sets the proxy server name for the test context.
public void setBaseUrl(String url)Sets the base URL for the test context.

Downloading and configuring jWebUnit in Eclipse

jWebUnit is implemented in pure Java code, so it's available as a JAR file (see Resources for the download link). After you download it, follow these steps to configure the jWebUnit library on the Eclipse platform:

  1. Extract the downloaded file, jwebunit-1.2.zip, into a temporary directory (assume C:\temp for our purposes).
  2. Create a new Java project in Eclipse named jWebUnit.
  3. Right-click on the jWebUnit project in Package Explorer view and select Properties.
  4. Click Java Build Path. In the Libraries tab, click Add External JARs.
  5. Browse to the C:\temp\jwebunit-1.2\lib directory and select all the JARs in this directory.
  6. Click OK.

Now you can start developing jWebUnit test cases in Eclipse under the jWebUnit project.


Building a sample application

It's time to see the jWebUnit API in action. I'll walk you through a sample application to help you better understand jWebUnit's true power. The application is a test case to open a Google search page and search for the text HttpUnit. You want the application to test the following scenarios:

  • Open the Google home page, http://www.google.com.
  • Assert that the page contains a form element with the name q. (On the Google home page, the text box named q is the one that takes a user query as input.) The application uses this element to enter the search criteria.
  • Enter the string HttpUnit Home into the search text box and submit the form.
  • Get the results page and assert that it contains a link containing the text HttpUnit Home.
  • Click on the link with the text HttpUnit Home.

Now that the test scenario is ready, you can write a Java application that uses jWebUnit to implement these requirements.

The first step is to declare a class that extends from WebTestCase, shown in Listing 3:

Listing 3. Declaring the testcase class
public class GoogleTest extends WebTestCase {
   static String searchLink = "";
}

As I mentioned earlier, jWebUnit requires every test case to extend from WebTestCase. searchLink stores the passed argument to search for. You pass this value as a command-line parameter to the test case.

The next step is to declare the entry point -- the main() method, shown in Listing 4:

Listing 4. The main() method
public static void main(String[] args) {
   searchLink = args[0];
   junit.textui.TestRunner.run(new TestSuite(GoogleTest.class));
}

The main() method executes the JTest test case by calling junit.textui.TestRunner.run(). Because you need to run the GoogleTest test case, the test suite you pass as parameter to run() method takes GoogleTest.class as an argument.

JTest calls the setUp() method next to set the base URL and proxy, as in Listing 5:

Listing 5. Setup
public void setUp() {
   getTestContext().setBaseUrl("http://www.google.com");
   getTestContext().setProxyName("proxy.host.com");
   getTestContext().setProxyPort(80);
}

Listing 5 sets the base URL to http://www.google.com. This means that the test case will start relative to this URL. The next two statements set the proxy host and proxy port to connect to the Internet. If you are directly connected to Internet, you can omit the proxy-setting statements.

Now you begin browsing the site and entering your search criteria. Listing 6 shows the code for accessing the Web page and then testing all the scenarios:

Listing 6. Testing the scenarios
public void testSearch() {
   beginAt("/");
   assertFormElementPresent("q");
   setFormElement("q", "HttpUnit");
   submit("btnG");
   assertLinkPresentWithText(searchLink);
   clickLinkWithText(searchLink);
}

The code in Listing 6 connects to the base URL and starts browsing relatively at /. Then it asserts that the page contains a form element with the name q -- the name of the query-entry text box on Google's home page. The next statement sets the text box with name q with the value HttpUnit. The next statement submits the form-submit button named btnG. (On Google's home page, the button named btnG is the button labeled Google Search.) In this conversation, the form is submitted and the next page lists the search results. On the results page, the code first checks if there is any link with the text HttpUnit Home. If the link isn't present, the test fails with AssertionFailedError. If the link is present, the test clicks on it.


Running the sample application

Now let's put the sample application to work:

  1. Download the sample application, j-webunitsample.jar (see Download).
  2. Unzip j-webunitsample.jar in a directory. If you extract it into C:\temp, for example, this places the source and class files into C:\temp\com\jweb\test and setclasspth.bat into C:\temp.
  3. Edit setclasspath.bat: Set JAR_BASE to point to the directory containing all the required JARs. For example, if you've extracted the jwebunit-1.2.zip file under C:\temp, set the JAR_BASE to C:\temp\jwebunit-1.2\lib.
  4. Open a command prompt and change directory to C:\temp.
  5. Execute setclasspath.bat. This sets the CLASSPATH required for the test case to execute.
  6. Run the application with the command java com.jweb.test.GoogleTest "HttpUnit Home".

Sample output

After you execute the test case, a test-case report prints out at the command prompt. If the test fails, the report looks like the one in Listing 7:

Listing 7. Output with assertion failure
C:\temp>java com.jweb.test.GoogleTest "HttpUnit Hwee"
.F
Time: 5.338
There was 1 failure:
1) testSearch(com.jweb.test.GoogleTest)junit.framework.AssertionFailedError: Link 
  with text [HttpUnit Hwee] not found in response.
at net.sourceforge.jwebunit.WebTester.assertLinkPresentWithText(WebTester.java:618)
at net.sourceforge.jwebunit.WebTestCase.assertLinkPresentWithText(WebTestCase.java:244)
        at com.jweb.test.GoogleTest.testSearch(GoogleTest.java:36)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at com.jweb.test.GoogleTest.main(GoogleTest.java:19)

FAILURES!!!
Tests run: 1,  Failures: 1,  Errors: 0

As you can see in Listing 7, the test case is executed with HttpUnit Hwee as a parameter. This test case will fail at assertion because the results page contains no link with this text. Hence the junit.framework.AssertionFailedError.

Listing 8 executes with HttpUnit Home as the parameter. The test case finds a link with this text, so it passes:

Listing 8. Successful test output
C:\temp>java com.jweb.test.GoogleTest "HttpUnit Home"
.
Time: 6.991

OK (1 test)

Conclusion

This article has given you a taste of the jWebUnit framework by discussing its salient features and most important classes and showing you how to use it to create a concise test case. jWebUnit has even more features you can use in your test cases. It lets your test count the number of links present on a Web page. You can assert that a string, table, or a form-input element with a given label is present or not present in the page. You can play with cookies, such as assert that a cookie is present, remove cookies, and so on. And your test can click on a link with particular text that appears after other text. If you want to build fast and efficient test cases for Web applications, jWebUnit just might be your best friend.


Download

DescriptionNameSize
Sample codej-webunitsample.jar2 KB

Resources

Comments

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 Java technology on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Java technology
ArticleID=83909
ArticleTitle=Create test cases for Web applications
publish-date=12162004