Technology Sharing

Automation (two positive)

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Technology stack used for Java interface automation

Technology stack summary:
①Java basics (encapsulation, reflection, generics, jdbc)
②Configuration file parsing (properties)
③httpclient (send http request)
④fastjson and jsonpath process data
⑤Key points of testng automated testing framework
⑥Allure test report

Category 1: http request related (fastjson, jsonpath, httpclient)

Prepare

Create a Maven Project

① First create a Maven project, newPROJECT–Maven—groupid----finish

insert image description here
insert image description here

② Check the Maven configuration again

File—settings—maven
insert image description here

Both fastjson and jsonpath are used to process data
The key points in the test automation framework.
Allure test report

1. fastjson (application scenario: parsing the input json string and string array)

Fastjson can process json strings and json arrays
Parse the json string input and prepare for subsequent requests

①Dependence

<!-https://mvnrepository.com/artifact/com.alibaba/fastjson -->
com.alibaba
fastison
1.2.75

②Add dependencies, and dependencies will be automatically generated

insert image description here
After downloading, you can see the automatically generated dependency package

1.1. Example (parsing json string input, json string array input)

1.1.1、Parse json string input

For example, you need a username and password to log in.
{“username”:“qzcsbj”, “password”:“123456”}

Automation framework data source, the input parameters are all json strings, fastjson is needed

Step 1: Create a package name, class name, and main method

insert image description here

Step 2: Define a string variable, which is the json string that needs to be parsed
Step 3: For the processing of json string, first parse it into jsonObject object and then put it into Map
1)First create a HashMap, key and value are both String

insert image description here
insert image description here

2) Parse the string. JSONObjetct.parseObject is used here, and the return value is of JSONObect type

Class.Method, this method is static

3) Get keys, directly use jsonObjetc.keySet method to get the Set collection

Each key in the collection is a String

4) Traverse again, get the value through the traversed key, and then put the key and value into the Map

insert image description here

The json string defined now has been parsed and put into the Map
insert image description here

5) Verify the content in the Map and get the key in the Map

Description: Put the contents of the json string into the map
blog.csdnimg.cn/direct/ae6feeba2eae442f961df977a6c8eac1.jpeg)

1.1.2、Parse json string array input

The automation framework involves initialization framework, and some need to operate the data inside. To operate the database, you need to write SQL
Here is a json array. In the array, each element is a json string, which contains key-value data. The first one is the sql number, the actual executed sql.

[{“sqlNo”:“1”,“sq!”:“select * from users where username=‘qzcsbj’;”},.“sqlNo”:“2”,“sql”:“select * from users where username=‘test00501’;”}]

Step 1: Create a package name, class name, and main method
Step 2: Define a string variable, which is the json string array that needs to be parsed
Method 1 (not advisable): Parse the string JSONObjetct.parseArray(String text), the return value is JSONArray
1) Parse the string, here we use JSONObjetct.parseArray

insert image description here

2) Direct traversal, each element is of Object type, and printed out as two json characters

insert image description here

3) Print the value of sql in the json string. There is no get or set method here. You can only get the json string, but not the content of a key.

insert image description here
This method is not advisable

Method 2: JSONObjetct.parseArray(String text, Class clazz), the return value is List&lt;T&gt;, the return type is List, and the return element is HashMap

Pass two parameters, the first parameter is the String to be parsed, and the second is the bytecode file
The solution is: parse the first parameter String into a Map

1) Encapsulate each element into a hashmap object. Here, JSONObjetct.parseArray(String text, Class clazz) is used to parse the string array.
2) Get sqlNo. sql is of HashMap type and can be used with the get method

insert image description here

3) No key value or type is obtained here, the default is Object, what we want here is String, which can be forced to convert, here polymorphism is used, the parent class reference points to the child class object
4) The value corresponding to each key in the json string in sql is obtained

insert image description here

5) Disadvantages of this method: It is troublesome to write many keys in the json string.
 String sqlNo = (String)sql.get("sqlNo");
  • 1
Method 3: Used to solve the shortcomings of method ⑤ in method 2, generally using encapsulation

Encapsulate the contents of each json string into an object l, add get and set methods in the entity class, directly use the object.get to get the sql content. This code prompt is also convenient to write. Automation also refers to this encapsulation. That is, encapsulate sql into an object,
Encapsulate the attributes into private (sqlNo, sql), provide get and set methods, and add the parameterized constructor and the non-parameterized constructor. Reflection will call the non-parameterized constructor. If you only write the parameterized constructor and do not write the non-parameterized constructor, you will definitely get an error. To print the string result, you need to add the toString() method, otherwise the address of the object will be printed. The above entity class is written.

Optimize it again
To encapsulate an element into an object, change it to a class you wrote.class
That is, sql.class

1) Define a javabean of sql: the sql class has attributes sqlNo, sql, and then add get, set methods, constructor, and toString() methods

insert image description hereinsert image description here

2) Encapsulate each json string into a sql object (Test02), JSONObjetct.parseArray(String text, Class clazz), the return value is List&lt;T&gt;, the return type is List, and the return element is the sql object

The second method above encapsulates each element into a hashMap object, while here each element is encapsulated into a sql object.
insert image description here

3) Traverse

To get properties from an object, just use the get method

insert image description here
This method is more convenient and does not require obtaining many keys.

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>mavenProject</groupId>
    <artifactId>mavenProject</artifactId>
    <version>1.0-SNAPSHOT</version>


    <dependencies>


        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.75</version>
        </dependency>

    </dependencies>

</project>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

SQL Class

package com.zhou.demo;

public class Sql {
    private String sql;
    private String sqlNo;

    public Sql() {
    }

    public Sql(String sql) {
        this.sql = sql;
    }


    public Sql(String sql, String sqlNo) {
        this.sql = sql;
        this.sqlNo = sqlNo;
    }

    public void setSql(String sql) {
        this.sql = sql;
    }

    public void setSqlNo(String sqlNo) {
        this.sqlNo = sqlNo;
    }

    public String getSql() {
        return sql;
    }

    public String getSqlNo() {
        return sqlNo;
    }

    @Override
    public String toString() {
        return "sql{" +
                "sql='" + sql + ''' +
                ", sqlNo='" + sqlNo + ''' +
                '}';
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
package com.zhou.demo;

import com.alibaba.fastjson.JSONObject;

import java.util.HashMap;
import java.util.Set;
//需求:将json字符串转化成map,字符串:{"username":"qzcsbj", "password":"123456"}

public class Test {
    public static void main(String[] args) {
        String parameters="{"username":"qzcsbj", "password":"123456"}";
        //先解析为JSONObject,然后转换为map
        HashMap<String, String> map = new HashMap<String, String>();

        // 解析json格式字符串为JSONObject(JSONObject是Map接口的一个实现类,和HashMap平级)

        JSONObject jsonObject = JSONObject.parseObject(parameters);
        // 将JSO\\\ NObject转换为map,先获取keys,先将keyset获取,集合里的每一个key都是String,通过遍历的key获取value,再放到map中
        Set<String> keys= jsonObject.keySet();
        for (String key:keys) {
            map.put(key,jsonObject.getString(key));

        }

        //验证,获取Map中的key
        Set<String> keys2 = map.keySet();
        for (String key :keys2) {
            System.out.println(key+"="+map.get(key));
        }

    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
package com.zhou.demo;

import com.alibaba.fastjson.JSONObject;

import java.util.HashMap;
import java.util.List;


//JSON数组,每个元素是json字符串
public class Test02 {

    public static void main(String[] args) {
        String initsql="[n" + "{"sqlNo":"1","sql":"select * from  users where  username='qzcsbj';"},n" +
                "{"sqlNo":"2","sql":"select * from  users where  username='tester00501';"}n" + "n" + "]";
  /*   //元素解析为Map
        List<HashMap> sqls = JSONObject.parseArray(initsql,HashMap.class);
        for (HashMap sql:sqls) {
            System.out.println(sql);
            String sqlNo = (String)sql.get("sqlNo");
            String sql_ = (String)sql.get("sql");
            System.out.println("sqlNo-"+sqlNo+",sql_-"+sql_);
        }*/



  //元素封装到对象
        List<Sql> sqls = JSONObject.parseArray(initsql, Sql.class);

        for (Sql sql:sqls) {
            String sqlNo = sql.getSqlNo();
            String sql_ = sql.getSql();
            System.out.println("sqlNo-"+",sql_"+sql_);

        }

    }


    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39

2. jsonpath (application scenario: parsing the response json data, such as obtaining assertion fields, such as the associated values ​​to be obtained)

Because currently the projects are separated in front and back ends
The backend generally returns a json string
If you want to make an assertion, you usually parse the JSON, and after parsing, you usually only make assertions on key fields.
Assertions are generally code + key business fields
It is a json string, so you need to use jsonpath

①Dependence

②Add dependencies, and dependencies will be automatically generated

blog.csdnimg.cn/5bdd9defd7db47b7a5934f79f9fd0ceb.png)
insert image description here
Need to confirm whether the dependencies are downloaded

2.1. Example (obtaining key business fields to be asserted in response data)

2.1.1. Get the key business fields to be asserted in the response data
Step 1: Create a class name, create a main method, and define a string variable

This variable here is the response field returned after successful login
blog.csdnimg.cn/a20e89ee243c43f69a1b4e1c3a97b89b.png)

Step 2: To make an assertion, you need to use Configuration.defaultConfiguration.jsonProvider().parse() to get the content inside, and the return value is of type Object

insert image description here
Pass the defined field response into

Step 3: Use the method JsonPath.read(Object json,String jsonpath,predicate…filters), the return type is Object type

insert image description here

Interface automation for processing dependent data
Get the token from the front of this line, which is also $.
After obtaining it, if it is a global variable, it can be saved in the global variable
If you want to get the assertion and then get
Make another assertion

3. httpclient (sending requests by writing code)

In the automation framework, requests are sent by writing code, which requires the use of httpclient, a library provided by java to interact with the server.

①Dependence

②Add dependencies, and dependencies will be automatically generated

insert image description here

3.1. Example (get request, post request)

3.1.1、get request
Preparation: Verify whether the request interface of the swagger interface document is valid, read the interface document, confirm the get request findById, and the id that needs to be passed

Need to pass id
insert image description here
From the library, I see that the ID is 259
insert image description here
insert image description here
insert image description here

Step 1: Create a class name Test04 and create a main method
Step 2: Define the interface address variable url and request parameters parameters

insert image description here
In the data file, parameters are concatenated into json strings, so id=259 is also concatenated into json strings.

Here, put 259 in double quotes to automatically escape it.
insert image description here

Step 3: Parse the JSON string using the JSONObject.parseObject() method. The return type is JSONObject.

insert image description here

Step 4: Define a static method getRequest(String url, JSONObject jsonobject)

insert image description here

Step 5: Call getRquest() in the main method again, and the return value is of String type

insert image description here

Step 6: Improve the getRequest() method logic

Get request: http://47.108.153.47:18089/qzcsbj/user/findById?id=259
? Then directly concatenate the parameters
There are also multiple values ​​to consider: http://47.108.153.47:18089/qzcsbj/user/findById?id=259&name=jack

1) Get the key through jsonobetct.keySet() to get a Set collection

insert image description here

2) Traverse the Set collection and get the key value

insert image description here

3) You also need to consider the case of multiple values, that is, define flag = true, write true first, and it is the first

insert image description here

4) Otherwise, write the following

insert image description here

5) Define a res empty string and return res

insert image description here
The above will concatenate the parameters of the url and parameters of the get request. After creating it, you need to create a get request object

6) Create an httpget request object, select new HttpGet (org.apache.http.client.methods) this constructor

Pass the url in
The httpget request object is obtained here
insert image description here

7) Create an httpclient client using the HttpClients.createDefault() method, and the return type is CloseableHttpClient

insert image description here

The CloseableHttpClient abstract class implements the HttpClient and Closeable interfaces.
insert image description here
Polymorphism can be used, and the subclass object points to the parent class reference (the interface implemented by the parent class)
insert image description here

8) Execute the request execute() method, pass the httpget object, and then throw an exception

insert image description here
insert image description here

9) After getting the HttpResponse object, you can call its getEntity method to get the Httpentity response object. After getting it, call the EntityUtils.toString method, and the return type is String.

insert image description here
insert image description here
The result res is defined above
Right now
insert image description here

10) Run

insert image description here

3.1.2, post request
Preparation: Verify that the request interface of the swagger interface document is valid

insert image description here
insert image description here

insert image description here

Step 1: Create a class named Test05 and create a main method

http://47.108.153.47:18089/qzcsbj/user/login
url, request parameters, request header

insert image description here

Step 2: Define the interface address variable url, request parameters parameters, request header

These parameters are obtained from data files in the automation framework
insert image description here
insert image description here

Step 3: Parse the JSON string para and headers using the JSONObject.parseObject() method. The return value is of type JSONObject.
Step 4: Define a method to send a post request, improve the logic, and pass the header, url, and parameters

Define res
Return res

insert image description here

1) Get the key through jsonobetct.keySet(), get a Set set, and traverse the key to get the key

insert image description here

2) If you want to call the addHeader() method through the httppost object, and the return type is HttPost, you need to create the httpppost object first

Pass URL
insert image description here

3) Call the addHeader() method through the httppost object

insert image description here

4) httpEntity is needed, but httpEntity is an interface, and interfaces cannot instantiate objects. You need to implement the class StringEntity to implement the interface httpEntity

insert image description here
insert image description here
Look at the constructor method can pass String, specify the second constructor

insert image description here
insert image description here
The above defines the post request: the request header and the data to be sent.

5) Create an httpclient client using the HttpClients.createDefault() method, and the return type is CloseableHttpClient

Subclass object points to parent class reference
insert image description here

6) Send a request, execute the request execute() method, pass the httppost object, and then throw an exception

insert image description here

7) After getting the HttpResponse object, you can call its getEntity method to get the Httpentity response object. After getting it, call the EntityUtils.toString method, and the return type is String

insert image description here

8) Call the method just defined in the main method

insert image description here

9) Run

insert image description here