Testing Web applications with HtmlUnit and WebSphere Studio

The open-source test framework JUnit and its extensions such as HtmlUnit provide many benefits for Web application testing, especially in extreme programming (XP) environments, and they are well integrated with WebSphere Studio. This article shows you how to use HtmlUnit with WebSphere Studio to test Web applications.

Share:

Christopher Wang (cpwang@us.ibm.com), XML Specialist, IBM

Christopher Wang is an XML Specialist at IBM with the ibm.com Innovation and Strategy team. He is a Brainbench Certified Web Developer and he received an M.S. in computer science in 1991 from New York University. You can reach Chris at cpwang@us.ibm.com



Ning Yan (nyan@us.ibm.com), Software Engineer, IBM

Ning Yan is a Software Engineer at IBM with the ibm.com Innovation and Strategy team. His expertise is in Web application development and business solutions that include DB2, WebSphere, and open-source technologies. He is an IBM Certified DB2 Specialist and Brainbench Certified Web Service Engineering and Web Developer, and he received an M.S. in computer science in 1996 from the State University of New York at Albany. You can reach Ning at nyan@us.ibm.com



01 September 2004

Introduction

HtmlUnit is one of the extended testing frameworks from JUnit. HtmlUnit models the returned document as HTML, so that you can deal with the document directly. HtmlUnit treats documentation as HTML with tags such as table, form, and so on. It still requires a Java™ test program that follows the JUnit testing framework structure.

In contrast with HttpUnit, HtmlUnit is not based directly on HTTP request/response actions, but instead requires you to write test cases based on HTML concepts such as links, forms, and tables. HtmlUnit has a Java API that provides the Java objects that enable the HTML documentation to be traversed as a DOM tree. In contrast with XMLUnit, HtmlUnit is specifically used for HTML and treats HTML as XML. However, you cannot use HtmlUnit to check for differences between two pieces of XML, or to check the XML that results from an XSLT transformation. HtmlUnit still fits into the black box test category. It brings up the extra choices for you to select the Java testing API, maintaining your test cases and testing manner for Web application testing. If an application Web page is constructed as XHTML, then you can still use HtmlUnit because XHTML will have a well formatted document structure.


Sample application

To demonstrate use of HtmlUnit, we can use the employee directory application on ibm.com. It's a WebSphere® J2EE application and the IBM® Web pages follow XHTML web standards. People outside IBM can search for IBM employee contact information as long as they know the employee's last name and country location.

Testing the IBM employee directory

  1. Go to the IBM home page at http://www.ibm.com and click Contact at the bottom.
  2. On the Contact IBM page, click Employee directory at lower right.
  3. On the Employee directory page, select the country from the drop-down list, enter the Last name and First name, and click Submit.
  4. Verify the search results. The content to be verified could be a page footer, metatags and header, and so on.
//application home
homePage = (HtmlPage)webClient.getPage(url);
assertNotNull(homePage);
//application link click
HtmlAnchor anchor = homePage.getAnchorByHref(ApplicationURLs.APP_SEARCH_PAGE);
assertNotNull(anchor);
try {
	employeesSearchPage = (HtmlPage) anchor.click();
	assertNotNull(employeesSearchPage);
} catch (IOException ioe) {
	ioe.printStackTrace();
}
//set the parameters for search
List formList = (List) employeesSearchPage.getAllForms();
HtmlForm searchForm = (HtmlForm) formList.get(1);

final HtmlSelect select = ( HtmlSelect )searchForm.getSelectsByName( "search_country" ).get( 0 );

select.setSelectedAttribute("ca", true);

//select.setSelectedAttribute("all", true);
final HtmlHiddenInput hiddenInput1 = (HtmlHiddenInput) searchForm.getInputByName("country");
hiddenInput1.setValueAttribute("us");
final HtmlHiddenInput hiddenInput2 = (HtmlHiddenInput) searchForm.getInputByName("language");
hiddenInput2.setValueAttribute("en");
final HtmlTextInput inputLastName = (HtmlTextInput)searchForm.getInputByName("lastname");
inputLastName.setValueAttribute("Shafi");
final HtmlTextInput inputFirstName = (HtmlTextInput)searchForm.getInputByName("firstname");
inputFirstName.setValueAttribute("Marie");
imageInput = (HtmlImageInput)searchForm.getInputByName("Submit");

try {
	searchResultPage = (HtmlPage)imageInput.click();
	assertNotNull(searchResultPage);

	Document resultsPage = searchResultPage.getDocument();

	//page content verification based on XML
	//It depends on html documentation structure its self,
	CommonTests.testResultsWhitespaceName(resultsPage, 
		"Employee Directory results page", "Shafi", "Marie");

} catch (Exception e) {
}

Test from WebSphere Studio

WebSphere Studio V5 or later is tightly integrated with the JUnit testing framework. In order to make your test case runnable from WebSphere Studio, you need to follow the basic JUnit test case programming API. For each test case. basically you need to extend your test class from TestCase. Then implement the methods setUp(), testXXXX(), and tearDown(). In order to make your test cases maintainable and reusable in a large project, please follow object-oriented design and other standard practices.

Before you set up the test, you need to have at a minimum the HtmlUnit binary JAR file. Extract the lib in a special directory. You can download a stable version of HtmlUnit 1.2.3 from SourceForge.

Create a Standalone Simple Java Project

Select File => New => Other. In the new window, select Java => Java project.

Figure 1. Simple Java Project.
Simple Java Project

Configure the Java build classpath for using HtmlUnit

In the new Java project dialog, select the Libraries tab and add the external JAR files from the lib directory. For HtmlUnit packages, add JUnit.jar, which you cab find in the WebSphere Studio plugin directory.

Figure 2. Test case build classpath configuration.
Test case build classpath configuration

Import Sample Application test code

Download HtmlUnit_JavaSrc.zip from end of this article and import the sample application into your Java project.

Run the test case

Highlight the test case or test suite which you need to test, Click on Run => Run as => JUnit.

Figure 3. Run JUnit
Run JUnit

Check the test result

Select the JUnit view from WebSphere Studio, and you can see the results running in color.

Figure 4. JUnit HtmlUnit test result
JUnit HtmlUnit test result

Run the test by Ant Script

    <target name="htmlunit" depends="compile">
    	<junit printsummary="yes" haltonfailure="yes">
    		<classpath refid="junit.classpath"/>
      		<formatter type="plain"/>
      		<test name="sample.testcase.IBMEmployeeDirectoryPageTest"
      			haltonfailure="no" outfile="test-result" todir="${build.dir}">
      		</test>
    	</junit>
    </target>

Download HtmlUnit_JavaSrc.zip from end of this article if you have not already done so and modify the build.xml file, specifying the build.dir, junit.jar, and htmlunit.libdir parameters.

  1. Configure WebSphere Studio using Ant. Select Window => Preferences and click on the Properties tab. Set build.compiler to org.eclipse.jdt.core.JDTCompilerAdapter.
    Figure 5. WebSphere Studio configuration setting for Ant.
    WebSphere Studio configuration setting for Ant
  2. Run the Ant script, and the results will be shown in the WebSphere Studio console. Right-click on build.xml and select Run Ant. The results will be shown in the console and the Ant output file.
    Figure 6. WebSphere Studio Ant runtime setting
    WebSphere Studio Ant runtime setting

Conclusion

HtmlUnit extends the JUnit Java test framework, offering additional choices for Web application testing. HtmlUnit lets you test Web applications by using HTML Web page concepts, and it works well when your Web content follows XHTML standards.


Download

DescriptionNameSize
Code sampleHtmlUnit_JavaSrc.zip  ( HTTP | FTP )7 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 WebSphere on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=WebSphere
ArticleID=23591
ArticleTitle=Testing Web applications with HtmlUnit and WebSphere Studio
publish-date=09012004