Compiled by senior veterans, a summary of Java interface automated testing, automating from 0 to 1...


Preface

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 cost of UI automation maintenance 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. .

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() is 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 the Json format type
. body(XMLdata) stores the XML format type
. formParam("Key", "Value") form parameter type.multipartFile
(new File(filePath))
.log().all() Print all
logs.relaxedHTTPSValidation() -- Handle the exception of invalid SSL certificate expiration

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() Get the value of a certain node in the return
res.asString () Get 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>  //如果使用更新的版本,JsonParser会被推荐不使用
</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

The following is the most comprehensive software testing engineer learning knowledge architecture system diagram in 2023 that I compiled.

1. Python programming from entry to proficiency

Please add image description

2. Practical implementation of interface automation projects

Please add image description

3. Web automation project actual combat

Please add image description

4. Practical implementation of App automation project

Please add image description

5. Resumes of first-tier manufacturers

Please add image description

6. Test and develop DevOps system

Please add image description

7. Commonly used automated testing tools

Please add image description

8. JMeter performance test

Please add image description

9. Summary (little surprise at the end)

Don't stop and don't give up on your dreams. In the face of difficulties and setbacks, only by firm belief and perseverance can we create our own shining glory and make life more colorful.

Face challenges bravely and persevere. Only through struggle can you write a magnificent chapter in life. On the way forward, constantly surpass yourself and move forward bravely, and you will eventually achieve a brilliant life.

Struggle is the password of life. Only by unlocking it can you reveal your glory. Regardless of difficulties and setbacks, if you persist in pursuing your dreams, you will eventually reap the joy of success and the glory of achievement.

Guess you like

Origin blog.csdn.net/csdnchengxi/article/details/134908428
Recommended