Original link:
Http://dev2dev.bea.com.cn/bbs/thread.jspa?forumid=124&threadid=8995&MessageId=45544
[Content Abstract] httpunit is an integrated test tool that focuses on the test of web applications, and the help class provides testers to interact with the Java class and the server and handle the server-side response to text or DOM objects. HttpUnit also provides an analog servlet container that allows you to test the internal code of the servlet without publishing a servlet. The author described in this paper describes how to complete the integration test using the classes provided by HTTPUnit.
Keywords: httpunit integration test
1 HTTPUNIT Introduction
HTTPUNIT is an open source project under SourceForge, which is a test framework based on JUnit, mainly focused on testing web applications, resolving the drawbacks of using the JUnit framework without testing the remote web content. The current latest version is 1.5.4. To make HTPUnit running normally, you should install JDK1.3.1 or above.
1.1 Working principle
HTTPUnit The Page Framework (FRIXIES), the HTTPUNIT, the page jump (redInce), and so on. With the function provided by HTTPUnit, you can interact with the server side, which will be processed as a common text, XML DOM object, or a collection of links, page frames, images, forms, tables, etc., and then use the JUnit framework Test, you can also guide a new page, then processes the new page, this feature allows you to handle a group in an operation chain.
1.2 Comparison of other commercial tools
Business tools generally use records, playback features to implement test, but there is a defect here that these recorded behaviors cannot be reused when the page design is modified, and the recording can continue to test.
For example: If there is an element in the page, the first design is a single option, this time you start testing, then these tools are recorded is your single-choice action, but if your design changes, like I Changed to drop-down selection, or use the text box to accept user input, this time, the test procedure you have previously recorded is invalid, and you must re-recording.
HTTPUNIT is because of the content of these controls, so it does not affect the reusability of your testing.
For more information on HTTPUnit, please visit httpunit's homepage
http://httpunit.sourceforge.net
2 author's demo environment
System platform: Windows 2000 SerCVER
Application Server: Shenzhen Kingdee APUSIC3.0
Development Tools: Eclipse 2.1.2
Description: All code please download the author's code.jar file.
3 HTTPUNIT installation, environment configuration
3.1 Installation
1. Homepage to HTTPUnit
Http://httpunit.sourceForge.net Download the latest package file, the current latest version is 1.5.4.
2. Will download. Zip Package compression to C: / httpunit (% httpUnit_home% will be used later) This directory)
3.2 Environmental configuration
The author's demo has been developed and implemented in Eclipse, so environmental configuration is Eclipse as an example. If you use other development tools, please configure it according to these steps.
1. Start Eclipse to create a Java project
2. Add% httpunit_home / lib / *. Jar;% httpunit_home% / jars / *. Jar Add to the Java Build Path variable of the Java project 4 How to use the HTTPUnit processing page
The WebConVersation class is the most important class in the HTTPUnit framework, which is used to simulate the behavior of your browser. Several other important classes are:
WebRequest imitates the customer request, which can send information to the server.
WebResponse Analog Browser Gets Response Information for Server End
4.1 Get the contents of the specified page
4.1.1 Get the page content directly
System.out.println ("Get the content directly:");
/ / Create a webconversation instance
WebConversation wc = new webconversation ();
/ / Send a request to the specified URL to get a response
WebResponse WR = wc.getResponse ("http:// localhost: 6888 / helloworld.html");
// Get all content with the GetText method
// Print the obtained content on the console with system.out.println
System.out.println (wr.gettext ());
4.1.2 Access the page via the GET method and add parameters
System.out.println ("Send data to the server, then get the web page content:");
/ / Create a webconversation instance
WebConversation wc = new webconversation ();
/ / Send a request to the specified URL
WebRequest Req = New GetMethodWebRequest ("http: // localhost: 6888 / helloworld.jsp");
// Add a parameter to the request
Req.SetParameter ("UserName", "Name");
// Get a response object
WebResponse resp = wc.getResponse (REQ);
// Get all content with the GetText method
// Print the obtained content on the console with system.out.println
System.out.println (Resp.getText ());
4.1.3 Access the page via the POST method and add parameters
System.out.println ("" Use the POST to send data to the server, then get the content: ");
/ / Create a webconversation instance
WebConversation wc = new webconversation ();
/ / Send a request to the specified URL
WebRequest Req = New PostMethodWebRequest ("http:// localhost: 6888 / helloworld.jsp");
// Add a parameter to the request
Req.SetParameter ("UserName", "Name");
// Get a response object
WebResponse resp = wc.getResponse (REQ);
// Get all content with the GetText method
// Print the obtained content on the console with system.out.println
System.out.println (Resp.getText ());
Everyone pays attention to the two contents of the underscore in the above code, it should beas to see that the difference between the use of the POST method access is different from the request objects.
4.2 Handling links in the page
The presentation here is to find a link in the page, then simulate the user's stand-alone behavior, get it to point to the contents of the file. For example, there is a link in my page helloWorld.html, which shows the contents of TestLink, pointing to my other page TestLink.htm. TestLink.htm only shows several characters in TestLink.html. Below is processing code:
System.out.println ("Get the contents of the page points to the page in the page:");
/ / Create a webconversation instance
WebConversation wc = new webconversation ();
// Get a response object
WebResponse Resp = Wc.getResponse ("http: // localhost: 6888 / helloworld.html");
// Get page link objects
WebLink Link = Resp.GetLinkWith ("TestLink");
// Simulate user clicking event
Link.click ();
// Get the current response object
WebResponse nextlink = wc.getcurrentpage ();
// Get all content with the GetText method
// Print the obtained content on the console with system.out.println
System.out.println (NextLink.getText ());
4.3 Treatment in Treatment Page
The table is used to control the regular objects displayed by the page, using an array in HTTPUnit to handle multiple tables in the page, and you can use the Resp.getTables () method to get all the table objects in the page. They are saved in a group in order in the order in the page.
[Note] The batch subscript in the Java starts from 0, so take the first table should be resp.gettables () [0], and other push.
The following example demonstrates how to remove the content of the first table from the page and display them to:
System.out.println ("Get the contents of the table in the page:");
/ / Create a webconversation instance
WebConversation wc = new webconversation ();
// Get a response object
WebResponse Resp = Wc.getResponse ("http: // localhost: 6888 / helloworld.html");
// Get the corresponding table object
WebTable WebTable = Resp.getTables () [0];
// Pass the content of the table object to the string array
String [] [] DATAS = WebTable.astext ();
// loop display table content
INT i = 0, J = 0;
INT M = Datas [0] .length;
INT n = DataS.Length;
While (i J = 0; While (j System.out.println ("Table" (i 1) "Row" (J 1) "column is:" Datas [J]); J;} i;} 4.4 Processing page The form form is used to accept user input, or display the user to the user has entered information (if you need user modifying data, us often display him. Previously entered information), use arrays in HTTPUnit to handle multiple forms in the page, and you can use the Resp.GetForms () method to get all the form objects for the page. They are saved in a group in order in the order in the page. [Note] The number of subscripts in Java starts from 0, so take the first form should be resp.getforms () [0], and other push. The following example demonstrates how to remove the content of the first form from the page and circulate them: system.out.println ("Get the contents of the form in the page:"); // Create a WebConversation instance WebconVersation WC = New WebConversation (); // Get the response object WebResponse resp = wc.getResponse ("http: // localhost: 6888 / helloworld.html"); // Get the corresponding form object WebForm Webform = Resp.GetForms () [0]; / / Get all the names of all controls in the form String [] pnames = Webform.getParameterNames (); int i = 0; int m = pnames.length; // loop display all controls in the form While (i For example, the page displayed in your expectation is a table, which is the first table in the page, and his first line of data should be display username, then you can use the following code to automate test: System.out.println ("Get the contents of the table in the page and test:"); // Create a WebConversation instance WebConversation wc = new webconversation (); // Get Response Object WebResponse Resp = Wc.getResponse ("http: / /localhost:6888/tabletest.html "); // Get the corresponding table object WebTable WebTable = Resp.getTables () [0]; // Transfer the content of the table object to the string array String [] [] DataS = WebTable .astext (); // Test string expect = "Chinese" on the table content; askERT.ASSERTEQUALS (Expect, Datas [0] [0]); 5.2 Test the servlet In addition to testing the page content, sometimes ( For example, when developing complex servlets), you need to test the code block of servlet itself, then you can choose HttpUnit, which can provide an analog servlet container that allows your servlet code to be released to servlet containers (such as Tomcat ) You can test it directly. 5.2.1 Principle Introduction Use the httpUnit to test the servlet, create a servletrunner instance, and he is responsible for analog Servlet container environments. If you just test a servlet, you can register this servlet directly, if you need to configure multiple servlets, you can write your own web.xml, then transfer it as a parameter to the Servletrunner when initializing the servletrunner. . When testing the servlet, you should remember to use the ServletUnitClient class as the client, he and the WebConversation used in front, inherits from WebClient, so their call mode is basically consistent. It is important to note that when using servletUnitclient, he ignores host address information in the URL, but directly points to the analog environment implemented by his servletrunner. 5.2.2 Simple Test This example only demonstrates how to simply access the servlet and get his output information. The servlet in the example is just returns a simple string when receiving the user request: Hello World! .1. Servlet code as follows: public class MyServlet extends HttpServlet {public void service (HttpServletRequest req, HttpServletResponse resp) throws IOException {PrintWriter out = resp.getWriter (); // write a string Hello World out.println ( "the browser to the // Create a servlet running environment servletrunner SR = new servletrunner (); // Register servlet sr.registerServlet ("INTERNALVLET", INTERNALVLET.CLASS.GETNAME ()); // Create a client servletUnitclient sc = Sr.NewClient (); // Send request WebRequest request = new getMethodWebRequest ("http: // localhost / internalservlet"); Request.SetParameter ("PWD", "PWD"); // Get the context environment invocationContext IC = sc.newinvocation (Request); // Call the non-service method of servlet InternalServlet IS = (InternalServlet) ic.getServlet (); is.mymethod (); // Directly get the request object directly through the context ("request) (" Request) The content acquired: " ic.getRequest (). GetParameter (" PWD ")); // Directly obtain the Response object through the context and output information Ic.getResponse () to the client side.. GetWriter (). Write (" Haha) "); // Get the session object directly through the context, control the session object // assign the session Ic.getRequest (). GetSession (). Setttribute (" username "," Timeson "); // Get 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 out WebResponse response = ic.getServletRESPONSE (); SYSTEM.out .println ()); [Note] Before testing servlet, you must complete the work completed in the service method in the Servlet through InvocationContext, because the method is not called when you get the InvocationContext instance through the newInvocation method.