Httpunit practice-

Source: Internet
Author: User

Download the htttp test framework from the httpunit website and decompress it to a specified directory. You can use index.htm to get instructions and examples in English.
The core of httpunit is webconversation, followed by webrequest and webresponse. The common usage is as follows.
Webconversation WC = new webconversation ();
Webrequest Req = new getmethodwebrequest ("http://www.meterware.com/testpage.html ");
Webresponse resp = WC. getresponse (req );

First, create a webconversation instance, and then you can use it to create an instance of the webrequest class and webresponse class, and then perform Web operations through these two instances. Let's look at an example. If our website is updated too quickly, there may be some situations where the hyperlink is not updated in time. The following test is a test class for this situation. It can report whether the hyperchains involved from an HTML webpage are correct.
/*
* Created by intellij idea.
* User: Champion
* Date: 2002-8-18
* Time: 21:02:35
* To Change template for new class use
* Code style | class templates options (tools | ide options ).
*/

Import com. meterware. httpunit. webconversation;
Import com. meterware. httpunit. weblink;
Import com. meterware. httpunit. webresponse;
Import JUnit. Framework. test;
Import JUnit. Framework. testcase;
Import JUnit. Framework. testsuite;

Import java. util. arraylist;

Public class testurls extends testcase {
Private webconversation WC;
Private string initurl = "http: // localhost/examples/jsp"; // you need to test the website directory or HTML webpage name.
Private string firsturl = "http: // localhost/examples/jsp"; // for a specified website, none of the webpages starting with this website will be tested.
Private arraylist URLs;

Public testurls (Java. Lang. String testname) {// Constructor
Super (testname );
}

Protected void setup () {// The preparation function before the test to initialize the list of tested webpages
URLs = new arraylist ();
}

Protected void teardown () {// clear the Array
URLs. Clear ();
}

Public static void main (Java. Lang. String [] ARGs) {// main test function
JUnit. textui. testrunner. Run (testurls. Class );
}

Public Static Test Suite (){
Testsuite suite = new testsuite (testurls. Class );
Return suite;
}

// Add test methods here, they have to start with 'test' name.
// For example:
Public void testhello () {// test function, which must start with test
WC = new webconversation (); // initialize httpunit

Assert (this. printurls (initurl, initurl ));

}

Private Boolean printurls (string fromurl, string URL) {// Private method, a recursive function used to test the webpage hyperlink
String eurl;

If (URL. Equals ("") return true;
Try {

Webresponse resp = WC. getresponse (URL); // return the response object in the specified path
URLs. Add (resp. geturl (). getprotocol () + ": //" + resp. geturl (). gethost () +
Resp. geturl (). getpath ());
If (resp. ishtml ()){
Weblink link [] = resp. getlinks ();

For (INT I = 0; I <link. length; I ++ ){
Weblink elink = link [I];
Eurl = elink. geturlstring ();
Eurl = encodeurl (eurl, resp); // format the URL
If (isthisweb (eurl) {// if it is on this site, continue
If (! URLs. Contains (eurl) {// if you have not accessed
System. Out. println (eurl );
Assert (printurls (URL, eurl ));

}
}
}
}
Return true;

} Catch (exception e ){
System. Err. println (E + "link from URL" + fromurl );
Return true;
}

}

Private Boolean isthisweb (string URL) {// returns whether the webpage belongs to this website
Return URL. indexof (firsturl)> = 0;
}

Private string encodeurl (string Surl, webresponse resp) {// convert the relative path to the absolute path.
String durl = "";
// If the result is returned to the root directory
If (Surl. startswith ("/") | Surl. startswith ("//") durl = resp. geturl (). getprotocol () + ": //" + resp. geturl (). gethost () + Surl;

// If it is a relative path
If (Surl. indexof ("HTTP") <0)
Durl = resp. geturl (). getprotocol () + ": //" + resp. geturl (). gethost () +
Resp. geturl (). getpath (). substring (0, resp. geturl (). getpath (). lastindexof ("/") + 1) + Surl;
If (Surl. indexof ("clr.html")> 0 ){
System. Out. println (durl );
System. Out. println (Surl );
}
// If the path contains a parent directory, convert it to an absolute path.
If (durl. indexof (".. ")> 0) durl = durl. substring (0, durl. lastindexof ("/", durl. indexof (".. ")-2) + durl. substring (durl. indexof (".. ") + 2 );
If (durl. Equals ("") durl = Surl;
Return durl;
}

}

I tested Tomcat's examples/jsp directory using this class and found two hyperlink errors.
Com. meterware. httpunit. httpnotfoundexception: Error on HTTP Request: 404 Not found [http: // localhost/examples/JSP/mail/snoop. JSP] link from URL http: // localhost/examples/JSP/mail/sendmail.html
Snoop. jsp cannot be accessed in sendmail.html.
Com. meterware. httpunit. httpnotfoundexception: Error on HTTP Request: 404 Not found [http: // localhost/examples/JSP/colors/clr.html.html] link from URL http: // localhost/examples/jsp
Unable to access http: // localhost/examples/JSP/index.html from http: // localhost/examples/JSP/colors/clr.html.html

The above example is just a simple access to the web page, which does not reflect the powerful functions of httpunit. Let's look at another example to see how httpunit interacts with webpages. There is a numguess game in Tomcat examples, and we will take it as an example. Numguess is a number from 1 to 100. if you guess a little bit, the webpage will prompt you to guess a bigger number. If you guess a little bit, you will be prompted to guess a smaller number. Until the guess is correct. This is the process of using form in get mode. Our test code is to make an automatic guess program that can interact with the website until the correct number is guessed. Below is the source code
/*
* Created by intellij idea.
* User: Champion
* Date: 2002-8-19
* Time: 8:18:46
* To Change template for new class use
* Code style | class templates options (tools | ide options ).
*/

Import JUnit. Framework. test;
Import JUnit. Framework. testsuite;
Import JUnit. Framework. testcase;
Import com. meterware. httpunit. webconversation;
Import com. meterware. httpunit. webresponse;
Import com. meterware. httpunit. webform;
Import com. meterware. httpunit. webrequest;

Import java. util. Random;

Public class testnumguess extends testcase {
Private webconversation WC;
Private string url = "http: // localhost/examples/JSP/num/numguess. jsp ";

Public testnumguess (Java. Lang. String testname ){
Super (testname );
}

Protected void setup (){
WC = new webconversation ();
}

Protected void teardown (){

}

Public static void main (Java. Lang. String [] ARGs ){
JUnit. textui. testrunner. Run (testnumguess. Class );
}

Public Static Test Suite (){
Testsuite suite = new testsuite (testnumguess. Class );
Return suite;
}

// Add test methods here, they have to start with 'test' name.
// For example:
Public void testgame (){
Int I, oldhigh = 100, oldlow = 1, temp;
Boolean issuccess = false;
Int times = 1;
Try {
I = (new random (). nextint (100 );
Webresponse resp = WC. getresponse (URL );
Webform forms [] = resp. getforms ();
Webrequest request = forms [0]. getrequest ();
While (! Issuccess ){
System. Out. println ("value =" + I + "You guess" + times + "times ");
Request. setparameter ("Guess", String. valueof (I ));
Resp = WC. getresponse (request );
Forms = resp. getforms ();
// Request = forms [0]. getrequest ();
If (resp. gettext (). indexof ("congratulations")> 0)
Issuccess = true;
Else if (resp. gettext (). indexof ("lower")> 0 ){
Temp = oldlow;
Oldhigh = I;
I = (I + temp)/2;
} Else if (resp. gettext (). indexof ("higher")> 0 ){
Temp = oldhigh;
Oldlow = I;
I = (I + temp)/2;
}
// System. Out. Print (resp. gettext (); // print the current webpage
Times ++;

}

Assert (issuccess );
} Catch (exception e ){
System. Err. println (E );
}

}

}

Result
Value = 89 you guess 1 times
Value = 45 you guess 2 times
Value = 67 you guess 3 times
Value = 56 you guess 4 times
Value = 50 you guess 5 times
Value = 47 you guess 6 times
Value = 48 you guess 7 times

Time: 1.031

OK (1 tests)

Indicates that the first guess is 89, the second guess is 45, and the Last guess is 48. The interaction core code has only three sentences.
Request. setparameter ("Guess", String. valueof (I ));
Resp = WC. getresponse (request );
Forms = resp. getforms ();

Setparameter can set a parameter value, and then use resp = WC. getresponse (request); send the configured webpage to the server, just as we manually enter the content on the webpage and press the submit button to send it to the server.

 

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.