Introduction to Interface Testing (3)--using httpclient for login use cases Operation/set-cookies Validation/list<namevaluepair> setting post parameters/json parsing

Source: Internet
Author: User

(recently learned are very basic interface testing, are based on UI interface visible interface, is to send requests, receive responses, analysis of the return of the results, checksum, the Common module encapsulation, only that, in fact, do the idea of automation is basically the case, the UI is also. )

Now start with the HttpClient comparison specification for a case that gets the company list (must be logged in first). First import HttpClient package will not say, many online.

Note: You must set user-agent and Referer, otherwise you will get an error.

  * idea:  
* issues that may need to be addressed:
* (1) How the login status remains
Span style= "font-family: ' Microsoft Yahei '; font-size:15px; " > * (2) post-login page redirection issue
* (3) How the post parameter is passed
* (4) The response obtained is a JSON string, how to parse it into the desired format, And extract the company list name (name)


(1) (2) Httclient will automatically process, (4) The first section describes the
(3): Use Post.setentity to pass in parameters, set parameters with list<namevaluepair>
Post.setheader ("User-agent", "Chrome");p Ost.setheader ("Referer", "passport.**.com"); ListNew arraylist<namevaluepair>();d ata.add(new Basicnamevaluepair (" Username "," 17710192*** "));d Ata.add (new basicnamevaluepair (" Password "," 123*** ");d Ata.add (  New Basicnamevaluepair ("type", "Login"));d ata.add ("Bind" , "false"));
Urlencodedformentity formentity = new urlencodedformentity (data);
Post.setentity (formentity);

The complete code is as follows:

 PackageCom.wyy.demo;ImportNet.sf.json.JSONArray;ImportNet.sf.json.JSONObject;Importorg.apache.http.*;ImportOrg.apache.http.Header;Importorg.apache.http.client.HttpClient;Importorg.apache.http.client.entity.UrlEncodedFormEntity;ImportOrg.apache.http.client.methods.HttpGet;ImportOrg.apache.http.client.methods.HttpPost;Importorg.apache.http.impl.client.HttpClients;ImportOrg.apache.http.message.BasicNameValuePair;Importorg.apache.http.util.EntityUtils;Importjava.util.ArrayList;Importjava.util.List; Public classCompanylist { Public Static voidMain (string[] args)throwsException {/*1. Set the interface URL to enter after login and login*/String loginurl= "Http://passport.36kr.com/***/sign_in";//set the interface URL for the login pageString Companyurl = "http://rongtest06.36kr.com/*********";//set the URL to get a list of companiesString loginverify = "http://rongtest06.36kr.com/*****"; /*2. Log in*/HttpClient HttpClient= Httpclients.createdefault ();//Define a connectorHttpPost post =NewHttpPost (loginurl);//set Request Send methodPost.setheader ("User-agent", "Chrome"); Post.setheader ("Referer", "passport.36kr.com"); List<NameValuePair> data =NewArraylist<namevaluepair>(); Data.add (NewBasicnamevaluepair ("username", "17710192039")); Data.add (NewBasicnamevaluepair ("Password", "123123123")); Data.add (NewBasicnamevaluepair ("type", "Login")); urlencodedformentity formentity=Newurlencodedformentity (data);   Post.setentity (formentity); //objects created by the Urlencodedformentity class can emulate parameters in a traditional HTML form transfer POST request     /*a cookie in the response header verifies that the cookie is formed*/HttpResponse Response= Httpclient.execute (post);//perform a POST requesthttpentity entity = response.getentity ();//Print out the contents of the responseSYSTEM.OUT.PRINTLN ("Content returned after login" + entityutils.tostring (Entity, "Utf-8")); System.out.println ("The first cookie is" + response.getfirstheader ("Set-cookie"))); System.out.println ("The last cookie is" + response.getlastheader ("Set-cookie"))); Header[] HS= Response.getheaders ("Set-cookie"); System.out.println ("The number of cookies is" +hs.length); /*3.get Request Login Authentication interface, determine whether the login success*/HttpGet Get1=NewHttpGet (loginverify); HttpResponse Response2=Httpclient.execute (GET1); Httpentity Entity2=response2.getentity (); System.out.println ("Return message after successful login:" + entityutils.tostring (entity2, "Utf-8"))); /*4. Get a list of companies*/HttpGet Get=NewHttpGet (Companyurl); HttpResponse response1=Httpclient.execute (GET); Httpentity entity1=response1.getentity (); String e= Entityutils.tostring (entity1, "Utf-8"); System.out.println (The JSON information returned by the Get company list is: "+e); /*5. JSON parsing of the returned information*/result result= Com.alibaba.fastjson.JSONObject.parseObject (E, Result.class);//corresponds to key one by one in the bean and JSONJsonobject Jsonobject = Jsonobject.fromobject (e);//Layer stripping, the first is to convert the jsonstring into a JSON objectString a = jsonobject.getstring ("Data");//extracts the value of the key:data of a JSON object, as a JSON stringJsonobject JsonObject1 = Jsonobject.fromobject (a);//Converts the value of data, JSON string, to a JSON objectJsonarray array = jsonobject1.getjsonobject ("page"). Getjsonarray ("Data");//get the number of company objects             for(inti = 0; I < array.size (); i++) {System.out.println ("The company list is:" +result.data.page.data.get (i). Company.name);//for loop output company Name value, ok!!!!!             }        }    }
Result.class content is as follows:
 PackageCom.wyy.demo;Importjava.util.ArrayList;Importjava.util.Date;Importjava.util.List;/*** Created by Wyy on 2016/4/7.*/ Public classResult { Public intCode;  PublicData1 data;  Public Static classdata1{ Publicpage page; }    Public  Static classpage{ Publiclist<data2> data =NewArraylist<>(); }     Public Static classdata2{ PublicComp Company; }    Public Static classcomp{ PublicString Operationstatus;  PublicDate updatedate;  PublicString name; }}
Cookies: cookie-related HTTP header: There are two HTTP headers and cookies about: Set-cookie and cookies.
In response to the request header: Set-cookie is sent by the server, which is included in the header of the response request. It is used to create a cookie on the client
in the request header: Thecookie header is sent by the client and is included in the header of the HTTP request. Note that only the domain and path of the cookie match the requested URL to send this cookie.


Note: All of the above operations use the same connection, keeping the same instance user.

The above are very nonstandard interface test cases, there are many problems:
1. How to encapsulate the login of different identity users and operate in Beforeclass
2. How to mix methods and use cases, which should be encapsulated as methods, and how use case classes should be organized
3.
How to encapsulate a domain name and interface as a URL to access
4. How to encapsulate different classes of requests like get, post without parameters, Post,put,delete with parameters
5. How to set the configuration file (mainly account and domain name)
6. How to encapsulate the return response
7. Encapsulation of common JSON format parsing
8. Assertion encapsulation, verifying results

Extracting common parts for encapsulation is a weakness ...

Introduction to Interface Testing (3)--using httpclient for login use cases Operation/set-cookies Validation/list<namevaluepair> setting post parameters/json parsing

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.