Using HttpUnit for integration testing

Source: Internet
Author: User
Tags gettext first row testlink

Content Summary

HttpUnit is an integrated testing tool that focuses on testing Web applications, providing help classes that allow testers to interact through Java classes and servers, and handle server-side responses as text or DOM objects. HttpUnit also provides a mock servlet container that allows you to test your servlet's internal code without the need to publish a servlet. The authors in this article will describe in detail how to use the classes provided by HttpUnit to complete the integration test.

1 HttpUnit Profile

HttpUnit is an open source project under SourceForge, a test framework based on JUnit that focuses on testing Web applications to address the drawbacks of using the JUnit framework to test remote Web content. The current latest version is 1.5.4. In order for Htpunit to work properly, you should install JDK1.3.1 or above.

1.1 Working principle

HttpUnit through the simulation of browser behavior, processing page frame (frames), cookies, page jump (redirects) and so on. With the functionality provided by HttpUnit, you can interact with the server side to make the returned Web page content as plain text, XML DOM objects, or as a collection of links, page frames, images, forms, tables, and so on, and then test using the JUnit framework. You can also guide a new page and then process the new page, which allows you to work with a group of pages in one chain of operations.

1.2 comparison with other business Tools

Business Tools generally use the recording, playback function to implement the test, but here is a flaw, when the page design is modified, these recorded behavior can not be reused, need to replay to continue testing.

For example, if you have an element on a page that is first designed with a single marquee, this time you start testing, then these tools record your individual selection action, but if your design changes, for example, if I change to a drop-down selection, or use a text box to accept user input, The test process you previously recorded was invalid and must be recorded again.

and HttpUnit because the focus is the content of these controls, no matter how your external manifestations change, it does not affect the reusability of the tests you have identified.

For more information on HttpUnit, please visit HttpUnit's homepage http://httpunit.sourceforge.net

2 Presentation Environment for authors

System platform: Windows Server

Application server: apusic3.0 of Shenzhen Kingdee

Development tools: Eclipse 2.1.2

3 HttpUnit installation, environment configuration

3.1 Installation

1. To HttpUnit's homepage http://httpunit.sourceforge.net Download the latest package file, the current latest version is 1.5.4.

2. Unzip the downloaded zip package to C:/httpunit (the directory will be referenced later using%httpunit_home%)

3.2 Environment Configuration

The author's demo program is developed and executed in eclipse, so the environment configuration is in eclipse as an example, if you use other development tools, follow these steps to configure the environment. Start Eclipse, build a Java project will%httpunit_home%/lib/*.jar; %httpunit_home%/jars/*.jar is added to the Java build path variable

4 How to use HttpUnit to process the contents of a page

The Webconversation class is the most important class in the HttpUnit framework, and it is used to simulate the behavior of browsers. Several other important classes are:

The WebRequest class, which imitates a customer request, can send information to the server.

WebResponse class, simulate the browser to obtain server-side response information.

4.1 Get the contents of the specified page

4.1.1 Get page content directly

SYSTEM.OUT.PRINTLN ("Direct access to Web content:");
Establish a webconversation instance
webconversation WC = new Webconversation ();

Sends a request to the specified URL to obtain a response
WebResponse WR = Wc.getresponse ("http://localhost:6888/HelloWorld.html");

The GetText method is used to obtain the corresponding whole content
//SYSTEM.OUT.PRINTLN the obtained content to print on the console
System.out.println (Wr.gettext ());

4.1.2 Access to the page through the Get method and add parameters

SYSTEM.OUT.PRINTLN ("Send data to the server, then get the page content:");
Establish a webconversation instance
webconversation WC = new Webconversation ();
Makes a request to the specified URL
WebRequest req = new Getmethodwebrequest ("http://localhost:6888/HelloWorld.jsp");
Add parameters to the request  
Req.setparameter ("username", "name");
Gets the response object
WebResponse resp = wc.getresponse (req);

The GetText method is used to obtain the corresponding whole content
//SYSTEM.OUT.PRINTLN the obtained content to print on the console
System.out.println (Resp.gettext ());

4.1.3 access to the page through the Post method and add parameters

SYSTEM.OUT.PRINTLN ("Send data to the server using post and get the page content:");
Establish a webconversation instance
webconversation WC = new Webconversation ();
Makes a request to the specified URL
WebRequest req = new Postmethodwebrequest ("http://localhost:6888/HelloWorld.jsp");
Add parameters to the request  
Req.setparameter ("username", "name");
Gets the response object
WebResponse resp = wc.getresponse (req);

The GetText method is used to obtain the corresponding whole content
//SYSTEM.OUT.PRINTLN the obtained content to print on the console
System.out.println (Resp.gettext ());

Attention to the above code underlined two things, you should be able to see, using GET, post methods to access the page is the difference between the requested object used.

4.2 Working with links in the page

The demo here is to find a link in the page, and then simulate the user's stand-alone behavior, to get it points to the contents of the file. For example, in my page helloworld.html there is a link, it shows the content is testlink, it points to my other page testlink.htm. testlink.htm shows only a few characters in testlink.html.

Here is the processing code:

System.out.println ("Get the contents of the link on the page to the page:");
Establish a webconversation instance
webconversation WC = new Webconversation ();
Gets the response object
WebResponse   resp = wc.getresponse ("http://localhost:6888/HelloWorld.html");
Get the page link object
weblink       link = resp.getlinkwith ("Testlink");
Simulate user Click event 
link.click ();
Gets the current response object
WebResponse   nextlink = Wc.getcurrentpage ();                                           
   
The GetText method is used to obtain the corresponding whole content
//SYSTEM.OUT.PRINTLN the obtained content to print on the console
System.out.println (Nextlink.gettext ());

4.3 processing the table in the page

A table is a regular object that controls the display of a page, using an array in HttpUnit to handle multiple tables in a page, and you can use the Resp.gettables () method to get all the table objects on the page. They are stored in an array in the order in which they appear in the page.

Attention In Java, array subscripts start at 0, so taking the first table should be Resp.gettables () [0], and so on.

The following example shows how to remove the contents of the first table from the page and display them in a loop:

System.out.println ("Get the contents of the table in the page:");
Establish a webconversation instance
webconversation WC = new Webconversation ();
Gets the response object
WebResponse   resp = wc.getresponse ("http://localhost:6888/HelloWorld.html");
Get the corresponding Table object
webtable webtable = resp.gettables () [0];
Passes the contents of the Table object to the string array
string[][] datas = Webtable.astext ();
Loop display table Contents
int i = 0, j = 0;
int m = datas[0].length;
int n = datas.length;
while (i<n) {
  j=0;
  while (j<m) {
    System.out.println ("table" + (i+1) + "row" +
 (j+1) + "column of the contents is:" +datas[i][j]);
    ++j;
  }
  ++i;
}

4.4 Working with forms in a page

The form is used to accept user input, or to show the user that the user has entered information (such as when the user needs to modify the data, usually displays the information he previously entered), use an array in HttpUnit to process multiple forms in the page, and you can use the resp.getforms () Method gets all the form objects on the page. They are stored in an array in the order in which they appear in the page.

Attention In Java, array subscripts start at 0, so the first form should be resp.getforms () [0], and so on.

The following example shows how to remove the contents of the first form from the page and display them in a loop:

System.out.println ("Get the contents of the form on the page:");
Establish a webconversation instance
webconversation WC = new Webconversation ();
Gets the response object
WebResponse   resp = wc.getresponse ("http://localhost:6888/HelloWorld.html");
Get the corresponding Form object
webform WebForm = resp.getforms () [0];
Get the names of all the controls in the form
string[] pnames = Webform.getparameternames ();
int i = 0;
int m = pnames.length;
Loop over the contents of all the controls in the form
while (i<m) {
   System.out.println (i+1) + "The name of the control is" +pnames[i]+
   ", which reads" + Webform.getparametervalue (Pnames[i]));
   ++i;
}

5 How to use HttpUnit for testing

5.1 Test the content of the page

This part of the test in HttpUnit completely employs the JUnit test method, which is to compare your desired results directly with the output from the page. But the test here is much simpler, just a comparison of strings and strings.

For example, the page you expect to display is a table that is the first table in the page, and his first row of the first column of data should be shown username, then you can use the following code for automated testing:

System.out.println ("Get the contents of the table in the page and test:");
Establish a webconversation instance
webconversation WC = new Webconversation ();
Gets the response object
WebResponse   resp = wc.getresponse ("http://localhost:6888/TableTest.html");
Get the corresponding Table object
webtable webtable = resp.gettables () [0];
Passes the contents of the Table object to the string array
string[][] datas = Webtable.astext ();
Test the contents of a table
String expect = "Chinese";
Assert.assertequals (Expect,datas[0][0]);

5.2 Testing the servlet

In addition to testing the content of the page, sometimes (for example, when developing complex servlets), you need to test the servlet's own block of code, at which point you can choose HttpUnit, which can provide a mock servlet container, Let your servlet code not be published to a servlet container (such as Tomcat) to test directly.

Introduction to 5.2.1 Principle

When testing a servlet using HttpUnit, create an instance of Servletrunner, which is responsible for simulating the servlet container environment. If you are just testing a servlet, you can register the servlet directly using the Registerservlet method, if you need to configure multiple servlet You can write your own web.xml and pass its position as an argument to the Servletrunner constructor when initializing the Servletrunner.

When testing the servlet, you should remember to use the Servletunitclient class as the client, he and the previous used webconversation almost, are inherited from the WebClient, so they are basically the same way of invocation. The difference to note is that when using servletunitclient, he ignores the host address information in the URL and points directly to his Servletrunner implementation's simulated environment.

5.2.2 Simple Test

This example only demonstrates how to simply access the servlet and get his output information, and the servlet in the example simply returns a string of simple strings when it receives a request from a user: Hello world!.

1. The code for the servlet is as follows:

public class Myservlet extends HttpServlet {public

 void service (HttpServletRequest req, HttpServletResponse resp) C2/>throws ioexception
 {
  PrintWriter out = Resp.getwriter ();
  Write a string to the browser Hello world!
  Out.println ("Hello world!");
  Out.close ();
 } 
          

2. The calling code for the test is as follows:

Create a servlet's running environment
Servletrunner sr = new Servletrunner ();
Registers the servlet
sr.registerservlet ("Myservlet", MyServlet.class.getName ()) to the environment;
Create a client that accesses the servlet
servletunitclient sc = sr.newclient ();
Send Request
WebRequest   = new Getmethodwebrequest ("Http://localhost/myServlet");
Get information on the analog server
WebResponse response = sc.getresponse (request);
Print the resulting results to the console
System.out.println (Response.gettext ());

5.2.3 Test the internal behavior of the servlet

It is not enough for developers to test only the request and return information, so the Servletrunner simulator provided by HttpUnit allows you to test the behavior within the called servlet. Unlike a simple test, this uses the Invocationcontext to get the servlet environment, and then you can use the Invocationcontext object for the request, An object such as response or an internal behavior of the servlet (a non-service method) is manipulated.

The following code demonstrates how to use HttpUnit to simulate the servlet container and, through the Invocationcontext object, tests most of the work of the servlet's internal behavior, such as controlling the request, session, response, and so on.

Create a servlet's running environment Servletrunner sr = new Servletrunner ();
Registers the servlet sr.registerservlet ("Internalservlet", InternalServlet.class.getName ()) to the environment;

Create a client that accesses the servlet servletunitclient sc = sr.newclient ();
Send Request WebRequest = new Getmethodwebrequest ("Http://localhost/InternalServlet");
Request.setparameter ("pwd", "pwd");
        
Gets the context environment for the request Invocationcontext IC = sc.newinvocation (request);
Calling the servlet's non-service method Internalservlet is = (internalservlet) ic.getservlet ();
     
Is.mymethod ();
     
Get the Request object System.out.println directly through the context ("content obtained from Request:" +ic.getrequest (). GetParameter ("pwd"));
     
The response object is obtained directly from the context, and the information is exported to the client Ic.getresponse (). Getwriter (). Write ("haha");
The session object is obtained directly through the context, and the Session object//session is assigned a value of Ic.getrequest (). GetSession (). setattribute ("username", "Timeson");
          
Gets the value of the session SYSTEM.OUT.PRINTLN (value in session: +ic.getrequest (). GetSession (). getattribute ("username"));
Use the client to get the return information and print it out webresponse response = Ic.getservletresponse (); System.out.println (REsponse.gettext ());
 

[note]

Before testing the servlet, you must complete the work done in the service method in the servlet through Invocationcontext. The method was not invoked because the Invocationcontext instance was fetched by the Newinvocation method.

6 Summary

In this article, the author demonstrates and describes how to use the class provided by HttpUnit to carry on the integration test, mainly realizes the following operation: The simulation user behavior sends the request to the server, passes the parameter to simulate the user to accept the server The response information, and through the auxiliary class analyzes these response information, Test the internal behavior of the servlet in development using the simulated Servler container provided by HttpUnit with the JUnit framework

reference materials HttpUnit help Http://httpunit.sourceforge.net JUnit help http://junit.org/index.htm

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.