The latest and most awesome Java code interface automated testing on the entire network REST Assured interface testing HTTPClient interface testing

Interface automation has become more and more popular in recent years. Compared with UI automation, interface automation has some advantages.

1. The operation is more stable than the UI, making it easier to locate bugs

2. The maintenance cost of UI automation is too high and the interface is relatively low.

There are actually many ways to test interfaces, mainly two. One is tools, the most common ones are: Postman, SoupUI, Jmeter; the other is code, which can be implemented in Java and Python.

The advantage of tools is that they are intuitive and quick to use. Some tools are also semi-automated and integrated, but tools still have certain limitations. Code is more versatile than tools. Use the interface testing framework combined with TestNG or Junit to realize interface automation. . This is an introduction to two common frameworks for implementing interface automation using Java code and how to handle interface return values.

1.REST Assured testing framework

maven coordinates

  <dependencies>
      <!-- https://mvnrepository.com/artifact/io.rest-assured/rest-assured -->
    <dependency>
        <groupId>io.rest-assured</groupId>
        <artifactId>rest-assured</artifactId>
        <version>4.0.0</version>
        <scope>test</scope>
    </dependency>
    
    <!-- https://mvnrepository.com/artifact/io.rest-assured/json-path -->
    <dependency>
        <groupId>io.rest-assured</groupId>
        <artifactId>json-path</artifactId>
        <version>4.0.0</version>
    </dependency>
      
      <!-- https://mvnrepository.com/artifact/io.rest-assured/json-schema-validator -->
    <dependency>
        <groupId>io.rest-assured</groupId>
        <artifactId>json-schema-validator</artifactId>
        <version>4.0.0</version>
    </dependency>
  </dependencies>

The official documentation recommends static import

import static io.restassured.RestAssured.*;
import static io.restassured.matcher.RestAssuredMatchers.*;
import static org.hamcrest.Matchers.*;

Syntax format

public void testExample()
{
        given()
                .queryParam("wd","mp3")
        .when()
                .get("http://www.baidu.com/s")
        .then()
                .log().all()
                .statusCode(200);
}

given() followed by the conditions required for a network request

.cookies() --cookies are stored in Map form

.contentType()

.queryParam("key","value") is used to get request parameters

.body(Jsondata) stores Json format type

.body(XMLdata) stores XML format type

.formParam("Key","Value") form parameter type

.multipartFile(new File(filePath)) 

.log().all() print all logs

.relaxedHTTPSValidation() --Handling invalid SSL certificate expiration exceptions 

Reference document: https://blog.csdn.net/u011541946/article/details/98892042

when() trigger condition

.get("url") 

.post("url")

.post("url/{key1}/{key2}",value1,value2)

then() assertion

.statusCode(200)

.body("key",hasItems("")) 

public Response testDemo(String corpid,String corpsecret ){
        Response res = RestAssured.given()
                .log().all()
                .when().get("https://baidu.com")
                .then().extract().response();
    
        return res;
    }
                

extract().response() Get the response result in response format

res.getCookie()

res.getHeader()

res.getStatusCode()

res.path("").toString() gets the value of a node in the return

res.asString() gets the returned content body

2. HttpClient

maven coordinates

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.5</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpcore</artifactId>
    <version>4.4.4</version>
</dependency>

import

import org.apache.http.HttpResponse;  
import org.apache.http.client.HttpClient;  
import org.apache.http.client.methods.HttpPost;  
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.HttpEntity; 

Simple example

 public String demoPost(String httpUrl) {
        String cookie ="JESSIONID=xxxxxxxx";
      String params = "JsonData";

        StringEntity stringEntity = new StringEntity(params, "UTF-8");  
        stringEntity.setContentType("application/x-www-form-urlencoded");  

        HttpPost httpPost = new HttpPost(httpUrl);    
        httpPost.setHeader(cookie,cookie);
        httpPost.setEntity(stringEntity);  

        HttpClient client = new DefaultHttpClient();
        HttpResponse Response = client.execute(httpPost); 
        String result = EntityUtils.toString(Response.getEntity());
    }      

 How to store cookies when logging in

CookieStore cookiestore=new BasicCookieStore();
CloseableHttpClient client1=HttpClients.custom().setDefaultCookieStore(cookiestore).build();

List<Cookie> cookies = cookiesstore.getCookies();

If the page has a redirection operation when logging in, you can also use cookieStore to store the cookies that need to be used for each redirection.

3. Jsonize the returned content

1.JSON

maven coordinates

        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20180130</version>
        </dependency>

array form response

JSONArray array = new JSONArray(response);
JSONObject object = array.getJSONObject(0);
String value = object.get("key").toString();

response with header information

JSONObject object = new JSONObject(response);
String value = object.getString("key");

2.gson (recommended)

 
 
<dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
  ​<version>2.8.2</version> //If a newer version is used, JsonParser will be recommended not to be used.
</dependency>
import com.google.gson.JsonParser;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

array form response

JsonPraser parser = new JsonParser();
JsonArray array = parser.parse(response).getAsJsonArray;
JsonObject object = array.get(0).getAsJsonObject();
String value = object.get("key").getAsString();

response with header information

JsonPraser parser = new JsonParser();
JsonObject object = parser.parse(response).getAsJsonOjbect();
JsonObject object_in = object.get("key").getAsJsonObject();
String value = object_in.get("key").getAsString();

getAsString() gets the value of the string

toString() gets the string

You can also use the fromJson() method provided by Gson to realize the conversion from Json related objects to Java entities.

import com.google.gson.Gson;
Gson gson = new Gson();
JsonObject object = gson.fromJson(response,JsonObject.class);

The above example converts Json string into JsonObject entity

You can also convert Json strings into classes written by yourself

  Recommended tutorials related to automated testing:

The latest automated testing self-study tutorial in 2023 is the most detailed tutorial for newbies to get started in 26 days. Currently, more than 300 people have joined major companies by studying this tutorial! ! _bilibili_bilibili

2023 latest collection of Python automated test development framework [full stack/practical/tutorial] collection essence, annual salary after learning 40W+_bilibili_bilibili

Recommended tutorials related to test development

The best in the entire network in 2023, the Byte test and development boss will give you on-site teaching and teach you to become a test and development engineer with an annual salary of one million from scratch_bilibili_bilibili

postman/jmeter/fiddler test tool tutorial recommendation

The most detailed collection of practical tutorials on JMeter interface testing/interface automated testing projects. A set of tutorials for learning jmeter interface testing is enough! ! _bilibili_bilibili

To teach yourself how to capture packets with fiddler in 2023, please be sure to watch the most detailed video tutorial on the Internet [How to Learn to Capture Packets with Fiddler in 1 Day]! ! _bilibili_bilibili

In 2023, the whole network will be honored. The most detailed practical teaching of Postman interface testing at Station B can be learned by novices_bilibili_bilibili

  Summarize:

 Optical theory is useless. You must learn to follow along and practice it in order to apply what you have learned to practice. At this time, you can learn from some practical cases.

If it is helpful to you, please like and save it to give the author an encouragement. It also makes it easier for you to search quickly next time.

If you don’t understand, please consult the small card below. The blogger also hopes to learn and improve with like-minded testers.

At the appropriate age, choose the appropriate position and try to give full play to your own advantages.

My path to automated test development is inseparable from plans at each stage, because I like planning and summarizing.

Test development video tutorials and study notes collection portal! !

Guess you like

Origin blog.csdn.net/m0_70618214/article/details/134864601