Integrated test using HTTPUNIT
[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 focusing on testing web applications, solving the drawbacks of the remote web content that cannot be tested using the JUnit framework. The current latest version is 1.5.4. To make HTPUnit running normally, you should install JDK1.3.1 or above. 1.1 Working Principles HTTPUNIT Through the analog browser's behavior, processing page frames (FRAMES), Cookies, page jump (redirects), etc. 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 and other commercial tools are generally recorded, playback features to implement test, but there is a defect here, that is, when the page design is modified, these recorded behaviors cannot be reused, and they need to re-recording to continue testing . 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.
More about httpunit, please visit httpunit's Home http://httpunit.sourceForge.Net/2 Author's Demo Environment System Platform: Windows 2000 SerCVER Application Server: Shenzhen Kingdee APUSIC 3.0 Development Tool: Eclipse 2.1.2
Description: All code please download the author's code.jar file. 3 HTTPUNIT installation, Environment Configuration 3.1 Installation 1. Home http://httpunit.sourceForge.net download the latest package file, the current latest version is 1.5.4. / 2. Download. ZIP Package compression to C: / httpunit (later will use% httpUnit_home% reference) 3.2 Environment Configuration Author's demo is developed, executed in Eclipse, so environmental configuration is Eclipse as an example, if you use For other development tools, please configure the environment based on these procedures. 1. Start Eclipse, establish a Java project 2. Put% httpunit_home / lib / *. Jar;% httpunit_home% / jars / *. Jar Add to the Java project of Java Build Path variables 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 imitating customer requests, by sending information to the server WebResponse analog browser Get server-side response information 4.1 Getting content 4.1.1 Direct access to the page content System.Out.println ("direct Get web content: "); // Establish a WebConversation instance Webconversation WC = New WebConversation (); // Send a request to the specified URL, get responding WebResponse WR = wc.getResponse (" http: // localhost: 6888 / helloworld. HTML "); // Get the appropriate content with the GetText method // Prints the obtained content on the console on the console using system.out.println; 4.1.2 passing through the GET method Access the page and join the parameter system.out.println ("Send data to the server, then obtain the web content:"); // create a WebConversation instance WebconVersation wc = new webconversation (); // Send a request WebRequest Req to the specified URL New getMethodWebRequest ("http: // localhost: 6888 / helloworld.jsp"); // give the request plus parameter Req.SetParameter ("UserName", "Name"); // Get Response Object WebResponse Resp = Wc.getResponse REQ);
// Get the appropriate content with the GetText method // Print the obtained content on the console on the console in system.out.println (resp.getText (); 4.1.3 Access the page via the POST method and join Parameters System.out.Println ("Use the POST mode to send data to the server, then obtain the web content:"); // to create a WebconVersation instance WebConversation wc = new webconversation (); // Send a request WebRequest Req = New to the specified URL PostmethodWebRequest ("http: // localhost: 6888 / helloworld.jsp"); // give the request plus the parameter Req.SetParameter ("UserName", "Name"); // Get Response Object WebResponse Resp = Wc.getResponse (REQ ); // obtain the corresponding content with the GetText method // Print the obtained content on the console on the console in system.out.println; use 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 Processing the link here This presentation is to find a link in the page, then simulate the user's stand-alone behavior, get what it points to 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. The following is the processing code: system.out.println ("Get the contents of the page pointing to the page:"); // Create a Webconversation instance WebConversation wc = new webconversation (); // Get Response Object WebResponse Resp = Wc.getResponse "http:// localhost: 6888 / helloworld.html"); // Get page link objects WebLink link = Resp.getLinkWith ("testlink"); // Simulate the user Click the event link.click (); // Get the current Response object WebResponse nextLink = wc.getcurrentpage ();
// Get the appropriate content with the getText method // Print the obtained content on the console on the console system.out.println (nextLink.getText ()); 4.3 Table Table Table Table in the Processing Page is used Control page displayed regular objects, use arrays 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 contents of the first table from the page and display them: system.out.println ("Get the contents of the table 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 table object WebTable WebTable = Resp.getTables () [0]; / / Transmit the content of the table object to the string array String [] [] data = webtable.astext (); // loop display table content int i = 0, j = 0; int m = Datas [0] .length; int; int n = DataS.Length; while (i 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 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 The following code demonstrates how to use the HTTPUnit to simulate the Servlet container, and test most of the work of the internal behavior of the servlet, such as control Request, Session, Response, and so on with the InvocationContext object. // 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. 6 Summary This article, the detailed demonstration of the author introduces how to use the classes provided by HTTPUnit to integrate tests, mainly implementing the following: 1. Simulate user behavior Send a request to the server, pass parameters 2. Simulate the user's response information, And analyzes these response information by assisted classes, combined with the JUnit framework for testing 3. Using the analog servler container provided by HTTPUnit, test the internal behavior of the servlet in the development. References: 1. httpunit Help http://httpunit.sourceforge.net/2. Junit Help http://junit.org/index.htm