Integrated test using HTTPUNIT

xiaoxiao2021-03-06  79

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.

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, visit httpunit.com http://httpunit.sourceforge.net

2 author's demo environment

System platform: Windows 2000 Server

Application Server: Shenzhen Kingdee APUSIC3.0

Development Tools: Eclipse 2.1.2

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. Complicate the downloaded ZIP packet to C: / httpunit (later will use% httpUnit_home% to reference 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.

To start Eclipse, establish a Java project to add% httpUnit_home / lib / *. Jar;% httpunit_home% / jars / *. Jar joined to the Java build path variable of the Java project.

4 How to use the HTTPUnit processing page content

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 classes, imitate customer requests, can send information to the server by it. WebResponse class, analog browser gets the response information of the server side.

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 to point to 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 content is: " DATAS [i] [j]);

J;

}

i;

}

4.4 Processing the form in the page

The form is used to accept user input, or the user can display the user has entered information (if the user needs to modify the data, the previously entered information is usually displayed), and the array is used in HTTPUnit to handle multiple forms in the page, You can get all the form objects for the page with the Resp.GetForms () method. 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 contents of the first form from the page and display them to:

System.out.println ("Get the contents of the form in the page:"); // Establish a WebConversation instance

WebConversation wc = new webconversation ();

// Get a response object

WebResponse Resp = Wc.getResponse ("http: // localhost: 6888 / helloworld.html");

// Get the corresponding form object

Webform Webform = Resp.GetForms () [0];

/ / Get the name of all controls in the form

String [] pnames = Webform.getParameterNames ();

INT i = 0;

INT m = pnames.length;

/ / Loop display content of all controls in the form

While (i

System.out.println ("Part (i 1) " The name of the control is " PNAMES [i]

", The content inside is" Webform.GetParameterValue (pnames [i]));

i;

}

5 How to use HTTPUNIT to test

5.1 Testing the page content

This part of this test in httpunit has completely compared the JUnit test method, which is directly compared to the output content you expect and the output content. However, the test here is more simple, just a comparison of strings and strings.

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 a response object

WebResponse Resp = Wc.getResponse ("http: // localhost: 6888 / tabletest.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 ();

/ / Test the content of the table

String eXpect = "Chinese";

AskERT.ASSERTEQUALS (Expect, Datas [0] [0]);

5.2 Testing Servlet

In addition to testing the page content, sometimes (for example, when developing complex servlets), you need to test the code block of the servlet itself. At this time you can choose HttpUnit, which can provide an analog servlet container that makes you The servlet code does not need to be released to the servlet container (such as Tomcat).

5.2.1 Principle

When you use the HTTPUnit to test the servlet, create a SERVLETRUNNER instance, and he is responsible for the analog Servlet container environment. 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. The code of the servlet is as follows:

Public class myservlet extends httpservlet {

Public Void Service (httpservletRequest Req, HttpservletResponse Resp)

Throws oException

{

PrintWriter out = Resp.getwriter ();

/ / Write a string Hello World!

OUT.PRINTLN ("Hello World!");

Out.close ();

}

}

2. The test call code is as follows:

// Create a servlet's operating environment

Servletrunner Sr = new servletrunner ();

/ / Register a servlet to the environment

Sr.registerServlet ("MyServlet", myservlet.class.getname ());

// Create a client that accesses the servlet

ServletUnitClient sc = sr.newclient ();

//send request

WebRequest Request = New GetMethodWebRequest ("http: // localhost / myservlet");

/ / Get information on the simulated server

WebResponse response = sc.getResponse (request);

// Print the result to the console

System.out.println (response.gettext ());

5.2.3 Test the internal behavior of servlet

For developers, only test requests and return messages are not enough, so the servletrunner simulator provided by HttpUnit allows you to test behaviors within the called servlet. In the simple test, INVOCATIONCONTEXT is used to get the servlet environment, and then you can operate with objects such as Request, ResponseText object or the internal behavior (non-service method) of the servlet.

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's operating environment

Servletrunner Sr = new servletrunner (); // Register a servlet to the environment

Sr.RegisterServlet ("InternalServlet", INTERNALSERVLET.CLASS.GETNAME ());

// Create a client that accesses the servlet

ServletUnitClient sc = sr.newclient ();

//send request

WebRequest Request = New getMethodWebRequest ("http:// localhost / internalservlet");

Request.SetParameter ("PWD", "PWD");

// Get the context environment of the request

InvocationContext IC = sc.newinvocation (request);

// Call the non-service method of servlet

INTERNALSERVLET IS = (INTERNALSERVLET) ic.getServlet ();

is.mymethod ();

/ / Get the Request object directly through the context

System.out.println ("The content obtained in Request:" ic.getRequest (). GetParameter ("PWD"));

/ / Directly obtain the Response object through the context and output information to the client

Ic.getResponse (). getWriter (). Write ("Haha");

/ / Get the session object directly through the context, control the session object

// Assign the session

Ic.getRequest (). getsession (). SetAttribute ("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 it out

WebResponse response = ic.getServletResponse ();

System.out.println (response.gettext ());

[note]

Before testing the 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

In this article, the author's detailed demonstration and introduce how to use the class provided by HTTPUnit to integrate test, mainly implementing the following:

The simulation user behavior sends a request to the server, transmitting parameters to simulate the user's response information, and analyzes these response information by secondary classes, combined with the JUnit framework for testing the simulated servler container provided by HttpUnit, testing the internal behavior of the servlet in the development

Reference

HTTPUNIT Help http://httpunit.sourceforge.net junit help http://junit.org/index.htm

About author

转载请注明原文地址:https://www.9cbs.com/read-121722.html

New Post(0)