1 HttpUnit Introduction
Httpunit is an open-source project under SourceForge. It is a testing framework based on JUnit. It focuses on testing web applications and solves the disadvantages of using the JUnit framework to test remote web content. The latest version is 1.5.4. To make htpunit run properly, you should install JDK 1.3.1 or later.
1.1 Working Principle
Httpunit simulates browser behavior, processes page frames (frames), cookies, and page jumps (redirects. With the functions provided by httpunit, you can interact with the server, process the returned webpage content as a common text, xml dom object, or a set of links, page frames, images, forms, and tables, and then use the JUnit framework for testing, you can also direct to a new page and then process the new page. This feature allows you to process a group of pages in an operation chain.
1.2 comparison with other commercial tools
Commercial tools generally use the record and playback functions for testing, but there is a defect here: After the page design is modified, these recorded behaviors cannot be reused, you need to record the file to continue the test.
For example, if one element on the page is first designed to adopt a single choice, and you start testing, these tools record your single choice action, however, if your design changes, for example, if I change it to a drop-down menu or use a text box to accept user input, the previously recorded test process will be invalid and you must record it.
Httpunit focuses on the content of these controls, so no matter how your external forms change, it does not affect the reusability of the tests you have determined.
For more information about httpunit, visit httpunit home page http://httpunit.sourceforge.net
2. Demo environment of the author
System Platform: Windows 2000 Server
Application Server: apusic3.0 of Shenzhen Kingdee
Development tools: Eclipse 2.1.2
3 HttpUnit installation and environment Configuration
3.1 Installation
1. download the latest package file from the httpunit home page http://httpunit.sourceforge.net, the latest version is 1.5.4.
2. decompress the downloaded zip package to C:/httpunit (this directory will be referenced using % httpunit_home % later)
3.2 Environment Configuration
The demo programs of the author are developed and executed in eclipse, so the environment configuration is based on Eclipse. If you use other development tools, perform environment configuration according to these steps.
- Start eclipse and create a java Project
- Add % httpunit_home %/lib/*. jar; % httpunit_home %/jars/*. jar to the java build Path variable of the Java project.
4. How to Use httpunit to process page content
The webconversation class is the most important class in the httpunit framework. It is used to simulate browser behavior. Other important classes are:
Webrequest class, which imitates a customer request and can send information to the server.
Webresponse class, simulate a browser to obtain the server response information.
4.1 get the content of the specified page
4.1.1 directly retrieve the page content
System. out. println ("directly retrieve webpage content:"); // create a webconversation instance webconversation WC = new webconversation (); // send a request to the specified URL, obtain the response webresponse wR = WC. getresponse ("http: // localhost: 6888/helloworld.html"); // use the gettext method to retrieve all the corresponding content. // use the system. out. println prints the obtained content on the console system. out. println (WR. gettext ());
4.1.2 access the page through the Get method and add Parameters
System. out. println ("send data to the server and then get the webpage content:"); // create a WebConversation instance WebConversation wc = new WebConversation (); // send a request WebRequest req = new GetMethodWebRequest ("http: // localhost: 6888/HelloWorld. jsp "); // Add the req parameter to the request. setParameter ("username", "name"); // obtain the response object WebResponse resp = wc. getResponse (req); // use the getText method to obtain all the corresponding content. // use System. out. println prints the obtained content on the console System. out. println (resp. getText ());
4.1.3 access the page through the Post method and add Parameters
System. out. println ("Use the Post method to send data to the server and then obtain the webpage content:"); // create a WebConversation instance WebConversation wc = new WebConversation (); // send a request WebRequest req = new PostMethodWebRequest ("http: // localhost: 6888/HelloWorld. jsp "); // Add the req parameter to the request. setParameter ("username", "name"); // obtain the response object WebResponse resp = wc. getResponse (req); // use the getText method to obtain all the corresponding content. // use System. out. println prints the obtained content on the console System. out. println (resp. getText ());
Let's take a look at the underlined content in the above Code. We can see that the difference between using the Get and Post methods to access the page is that different request objects are used.
4.2 process links on the page
The demonstration here is to find a link on the page, and then simulate the user's standalone behavior to obtain the content that points to the file. For example, if there is a link in my page helloworld.html, the content shown in the link is testlink. the link only displays testlink.html characters in another page.
The following is the processing code:
System. out. println ("Get the content of the link on the page pointing to the page:"); // create a webconversation instance webconversation WC = new webconversation (); // obtain the response object webresponse resp = WC. getresponse ("http: // localhost: 6888/helloworld.html"); // obtain the weblink link = resp. getlinkwith ("testlink"); // simulates the user's clicking event link. click (); // obtain the current response object webresponse nextlink = WC. getcurrentpage (); // use the gettext method to obtain all the corresponding content. // use system. out. println prints the obtained content on the console system. out. println (nextlink. gettext ());
4.3 Process tables on the page
Tables are common objects used to control page display. In httpunit, arrays are used to process multiple tables on the page. You can use resp. gettables () to obtain all table objects on the page. They are stored in an array in the order they appear in the page.
[Note] the array subscript in Java starts from 0, so the first table should be resp. gettables () [0], and so on.
The following example shows how to retrieve the content of the first table from the page and display them cyclically:
System. out. println ("retrieve table content on the page:"); // create a webconversation instance webconversation WC = new webconversation (); // obtain the response object webresponse resp = WC. getresponse ("http: // localhost: 6888/helloworld.html"); // obtain the corresponding table object webtable = resp. gettables () [0]; // pass the table object content to the string array string [] [] datas = webtable. astext (); // cyclically display the table content int I = 0, j = 0; int M = datas [0]. length; int n = datas. length; while (I <n) {J = 0; while (j <m) {system. out. the content of the println ("table" + (I + 1) + "row" + (J + 1) + "column is: "+ datas [I] [J]); ++ J ;}++ I ;}
4.4 process forms on the page
A form is used to accept user input. It can also display user input information to the user. (If you need to modify data, the information previously entered is usually displayed ), use arrays in httpunit to process multiple forms on the page. You can use resp. the getforms () method gets all form objects on the page. They are stored in an array in the order they appear in the page.
[Note] the array subscript in Java starts from 0, so the first form should be resp. getforms () [0], and so on.
The following example shows how to retrieve the content of the first form from the page and display them cyclically:
System. out. println ("retrieve the Form Content on the page:"); // create a WebConversation instance WebConversation wc = new WebConversation (); // obtain the response object WebResponse resp = wc. getResponse ("http: // localhost: 6888/HelloWorld.html"); // obtain the corresponding form object WebForm webForm = resp. getForms () [0]; // obtain the names of all controls in the form String [] pNames = webForm. getParameterNames (); int I = 0; int m = pNames. length; // The while (I <m) {System. out. the name of the println ("Number" + (I + 1) + "control is" + pNames [I] + ", and the content is" + webForm. getParameterValue (pNames [I]); ++ I ;}
5. How to Use httpunit for testing
5.1 test the page content
The tests in httpunit fully adopt the JUnit test method, that is, you can directly compare the expected results with the output content on the page. However, the test here is much simpler, just a comparison between strings and strings.
For example, the expected page display contains a table, which is the first table on the page, and the data in the first column of the First row should be username, then you can use the following code for automated testing:
System. out. println ("obtain and test the table content on the page:"); // create a WebConversation instance WebConversation wc = new WebConversation (); // obtain the response object WebResponse resp = wc. getResponse ("http: // localhost: 6888/TableTest.html"); // obtain the corresponding table object WebTable webTable = resp. getTables () [0]; // pass the table object content to the String array String [] [] datas = webTable. asText (); // test the table content String exercise Ct = "Chinese"; Assert. assertEquals (expect, datas [0] [0]);
5.2 Test the Servlet
In addition to testing the page content, sometimes (for example, when developing complicated Servlets), you need to test the Servlet code block. In this case, you can choose HttpUnit, it provides a simulated Servlet container so that your Servlet code can be directly tested without being published to the Servlet container (such as tomcat.
5.2.1 principles
When using httpunit to test the Servlet, create a ServletRunner instance to simulate the Servlet container environment. If you only test a Servlet, you can directly use the registerServlet method to register the Servlet. If you need to configure multiple Servlets, you can write your own web. xml, and then send its location as a parameter to the constructor of ServletRunner when initializing ServletRunner.
When testing the Servlet, remember to use the ServletUnitClient class as the client. It is similar to the previously used WebConversation and all inherit from the WebClient, so their call methods are basically the same. Note that when using ServletUnitClient, the host address information in the URL is ignored, but directly directed to the simulation environment implemented by his ServletRunner.
5.2.2 simple test
This example only demonstrates how to access the Servlet and obtain its output information. In this example, when the Servlet receives a user request, it returns a simple string: Hello World !.
1. The Servlet code is 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 to the browser! Out. println ("Hello World! "); Out. close ();}}
2. The call code for the test is as follows:
// Create the Servlet runtime environment ServletRunner sr = new ServletRunner (); // register Servletsr with the environment. registerServlet ("myServlet", MyServlet. class. getName (); // create the Servlet access client ServletUnitClient SC = sr. newClient (); // send the request WebRequest request = new GetMethodWebRequest ("http: // localhost/myServlet"); // obtain the information of the simulation server WebResponse response = SC. getResponse (request); // print the result to the console System. out. println (response. getText ());
5.2.3 test internal Servlet Behavior
For developers, testing requests and returned information alone is not enough. Therefore, the servletrunner simulator provided by httpunit allows you to test the internal behavior of the called servlet. Different from the simple test, invocationcontext is used to obtain the servlet environment. Then, you can use the invocationcontext object to view the request, response, and other objects or internal behavior of the servlet (non-service method).
The following code demonstrates how to use httpunit to simulate the servlet container and test the internal behavior of the servlet through the invocationcontext object, such as controlling request, session, and response.
// Create the Servlet runtime environment ServletRunner sr = new ServletRunner (); // register Servletsr with the environment. registerServlet ("InternalServlet", InternalServlet. class. getName (); // create the Servlet access client ServletUnitClient SC = sr. newClient (); // send the request WebRequest request = new GetMethodWebRequest ("http: // localhost/InternalServlet"); request. setParameter ("pwd", "pwd"); // obtain the context of the request. InvocationContext ic = SC. newInvocation (request); // call the Servlet's non-service method InternalServlet is = (InternalServlet) ic. getServlet (); is. myMethod (); // obtain the request object System directly through the context. out. println ("content obtained in request:" + ic. getRequest (). getParameter ("pwd"); // get the response object directly through the context and output the information ic to the client. getResponse (). getWriter (). write ("haha"); // get the session object directly through the context and control the session object // assign the ic to the session. 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 obtain the returned information and print out WebResponse response = ic. getServletResponse (); System. out. println (response. getText ());
[Note]
Before testing the Servlet, you must use InvocationContext to complete the work in the service method of the Servlet, because the method is not called when the InvocationContext instance is obtained through the newInvocation method.
6. Conclusion
In this article, the author demonstrates in detail and describes how to use the classes provided by HttpUnit for integration testing, mainly to achieve the following operations:
- Sends a request to the server by simulating user behavior and passing Parameters
- Simulate that the user accepts the server response information, analyze the response information through the auxiliary class, and test the response based on the JUnit framework.
- Use the Servler container provided by HttpUnit to test the internal behavior of the Servlet in development
References
- HttpUnit help http://httpunit.sourceforge.net
- JUnit help http://junit.org/index.htm