当前位置:   article > 正文

Java+TestNG+HttpClient接口自动化测试框架_java+httpclient+maven+testng框架实现接口自动化流程

java+httpclient+maven+testng框架实现接口自动化流程

1.HttpClient作用

模拟客户端发送请求

2.测试框架搭建

(1)JDK环境

网上有很多

(2)TestNG引入

接口自动化入门-TestNg

(3)HttpClient引入

在maven项目的pom.xml中引入如下两个依赖

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

        <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.6</version>
        </dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

3.发送Get请求和post请求

如果post提交的是json类型数据,需要在pom.xml中添加依赖:

 		<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.76</version>
        </dependency>
  • 1
  • 2
  • 3
  • 4
  • 5

get请求:

// 准备url
 String url="http://www.baidu.com";
 //请求方法
HttpGet get = new HttpGet(url);
//请求头
 get.setHeader("Authorization",tokenV);
 //准备一个发送请求的客户端
 CloseableHttpClient httpClient = HttpClients.createDefault();
 // 发送请求得到响应报文-java中封装为对象
 CloseableHttpResponse response = httpClient.execute(get);
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

post请求

		String url="http://www.baidu.com";
        HttpPost post=new HttpPost(url);
        //添加请求头
        post.setHeader("Content-Type","application/json");
        //准备post参数
//        -- 1-json类型
        JSONObject json = new JSONObject();
        json.put("username","admin");
        json.put("password","123456");
        System.out.println("请求参数:"+json);
// 发送 json 类型数据,通过new StringEntity(),可将Content-Type设置为text/plain类型
        post.setEntity(new StringEntity(json.toString(),"UTF-8"));
         //创建发请求的客户端
        CloseableHttpClient httpClient=HttpClients.createDefault();
        //获得响应内容
        CloseableHttpResponse response=httpClient.execute(post);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

实际项目展示

import com.alibaba.fastjson.JSONObject;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

/**
 * @author zhaomin
 * @date 2023/4/6 16:34
 */
public class CategoriesTest {
    //URL会变、参数会变、请求头会变
    //    @BeforeMethod
    @Test(dependsOnMethods = {"getToken"})
    public void getCategories() throws ClientProtocolException, IOException {

        //    请求Url
        String url = "http://127.0.0.1:8888/api/private/v1/categories?type=1";
        Single token=Single.INSTANCE;
        String tokenV=token.getValue();
//        请求方法
        HttpGet get = new HttpGet(url);
        get.setHeader("Authorization",tokenV);
//        准备一个发送请求的客户端
        CloseableHttpClient httpClient = HttpClients.createDefault();
//        发送请求得到响应报文-java中封装为对象
        CloseableHttpResponse response = httpClient.execute(get);
        //状态行
        StatusLine statusLine = response.getStatusLine();
//        加断言-- todo
        System.out.println(statusLine.getReasonPhrase());
        System.out.println(statusLine.getStatusCode());
        System.out.println(statusLine.getProtocolVersion());
//        响应头
        Header[] headers = response.getAllHeaders();
        for (Header item : headers
                ) {
            System.out.println(item);
        }
//        响应体
        HttpEntity entity = response.getEntity();
        String entityString = EntityUtils.toString(entity);
//        加断言-- todo
//        System.out.println(entity);
        System.out.println(entityString);

    }

    @Test
    public void getToken() throws ClientProtocolException, IOException {
        String url="http://127.0.0.1:8888/api/private/v1/login";
        HttpPost post=new HttpPost(url);
        //添加请求头
        post.setHeader("Content-Type","application/json");
//        post.setHeader("Content-Length","3843");

        //准备post参数
//        -- 1-json类型
        JSONObject json = new JSONObject();
        json.put("username","admin");
        json.put("password","123456");
        System.out.println("请求参数:"+json);
// 发送 json 类型数据,通过new StringEntity(),可将Content-Type设置为text/plain类型
        post.setEntity(new StringEntity(json.toString(),"UTF-8"));

        //--2-准备普通类型参数
        /*
        List<NameValuePair> parameters=new ArrayList<NameValuePair>();
        parameters.add(new BasicNameValuePair("username","admin"));
        parameters.add(new BasicNameValuePair("password","123456"));
        HttpEntity requestEntity=new UrlEncodedFormEntity(parameters);
        post.setEntity(requestEntity);
        */

        //创建发请求的客户端
        CloseableHttpClient httpClient=HttpClients.createDefault();

        //获得响应内容
        CloseableHttpResponse response=httpClient.execute(post);
        StatusLine statusLine = response.getStatusLine();
        HttpEntity entity=response.getEntity();
        System.out.println(entity);
        String entityString=EntityUtils.toString(entity);
        JSONObject jsonObj=JSONObject.parseObject(entityString);
        String status=jsonObj.getJSONObject("meta").getString("status");
        Assert.assertEquals("200",status,"获取token失败");
        String tokenV=jsonObj.getJSONObject("data").getString("token");

//        entityString.en
        Single token=Single.INSTANCE;
        token.setKey("token");
        token.setValue(tokenV);
        System.out.println(token.getKey());
        System.out.println(entityString);

    }
    
}
  • 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
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119

4.发送post请求

import com.alibaba.fastjson.JSONObject;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

/**
 * @author zhaomin
 * @date 2023/4/6 16:34
 */
public class CategoriesTest {
    //URL会变、参数会变、请求头会变
    //    @BeforeMethod
    @Test(dependsOnMethods = {"getToken"})
    public void getCategories() throws ClientProtocolException, IOException {

        //    请求Url
        String url = "http://127.0.0.1:8888/api/private/v1/categories?type=1";
        Single token=Single.INSTANCE;
        String tokenV=token.getValue();
//        请求方法
        HttpGet get = new HttpGet(url);
        get.setHeader("Authorization",tokenV);
//        准备一个发送请求的客户端
        CloseableHttpClient httpClient = HttpClients.createDefault();
//        发送请求得到响应报文-java中封装为对象
        CloseableHttpResponse response = httpClient.execute(get);
        //状态行
        StatusLine statusLine = response.getStatusLine();
//        加断言-- todo
        System.out.println(statusLine.getReasonPhrase());
        System.out.println(statusLine.getStatusCode());
        System.out.println(statusLine.getProtocolVersion());
//        响应头
        Header[] headers = response.getAllHeaders();
        for (Header item : headers
                ) {
            System.out.println(item);
        }
//        响应体
        HttpEntity entity = response.getEntity();
        String entityString = EntityUtils.toString(entity);
//        加断言-- todo
//        System.out.println(entity);
        System.out.println(entityString);

    }

    @Test
    public void getToken() throws ClientProtocolException, IOException {
        String url="http://127.0.0.1:8888/api/private/v1/login";
        HttpPost post=new HttpPost(url);
        //添加请求头
        post.setHeader("Content-Type","application/json");
//        post.setHeader("Content-Length","3843");

        //准备post参数
//        -- 1-json类型
        JSONObject json = new JSONObject();
        json.put("username","admin");
        json.put("password","123456");
        System.out.println("请求参数:"+json);
// 发送 json 类型数据,通过new StringEntity(),可将Content-Type设置为text/plain类型
        post.setEntity(new StringEntity(json.toString(),"UTF-8"));

        //--2-准备普通类型参数
        /*
        List<NameValuePair> parameters=new ArrayList<NameValuePair>();
        parameters.add(new BasicNameValuePair("username","admin"));
        parameters.add(new BasicNameValuePair("password","123456"));
        HttpEntity requestEntity=new UrlEncodedFormEntity(parameters);
        post.setEntity(requestEntity);
        */

        //创建发请求的客户端
        CloseableHttpClient httpClient=HttpClients.createDefault();

        //获得响应内容
        CloseableHttpResponse response=httpClient.execute(post);
        StatusLine statusLine = response.getStatusLine();
        HttpEntity entity=response.getEntity();
        System.out.println(entity);
        String entityString=EntityUtils.toString(entity);
        JSONObject jsonObj=JSONObject.parseObject(entityString);
        String status=jsonObj.getJSONObject("meta").getString("status");
        Assert.assertEquals("200",status,"获取token失败");
        String tokenV=jsonObj.getJSONObject("data").getString("token");

//        entityString.en
        Single token=Single.INSTANCE;
        token.setKey("token");
        token.setValue(tokenV);
        System.out.println(token.getKey());
        System.out.println(entityString);

    }
    
}
  • 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
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119

post请求封装

如果有多个post请求时,不用每次都写重复。

@Test
    public String post(String url, HashMap<String,String> paramsMap)throws ClientProtocolException, IOException{
        HttpPost post=new HttpPost(url);
        //参数
        Set<String> keySet=paramsMap.keySet();
        JSONObject json = new JSONObject();
        for(String item:keySet){
            json.put(item,paramsMap.get(item));
        }
        // 发送 json 类型数据,通过new StringEntity(),可将Content-Type设置为text/plain类型
        post.setEntity(new StringEntity(json.toString(),"UTF-8"));
        CloseableHttpClient httpClient=HttpClients.createDefault();
        CloseableHttpResponse response=httpClient.execute(post);
        HttpEntity entity=response.getEntity();
        String entityString = EntityUtils.toString(entity);
        return entityString;

    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号