封装get和post接口的请求并断言

 

先看看项目目录:

一:第一步先创建一个maven项目,其中pom文件的的依赖如下

<dependencies>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.11</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.9</version>
        </dependency>
</dependencies>

二:可以看到我们还有一个properties的配置文件,该文件目前就一个host,以后的各种key-value形式的数据都可以用配置文件进行维护(当然用数据库存储或者excel表格也是可以的,这里不涉及)

三:然后我们来写一个基础类用来读取配置文件中的key,定义的状态码是为了以后做断言用的,你也可以先不写这个,直接注释掉也是可以的

package com.yufeng.httpclient.base;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

public class TestBase {
    public Properties prop;
    public int RESPNSE_STATUS_CODE_200 = 200;
    public int RESPNSE_STATUS_CODE_201 = 201;
    public int RESPNSE_STATUS_CODE_404 = 404;
    public int RESPNSE_STATUS_CODE_500 = 500;


    //写一个构造函数
    public TestBase() {

        try {
            prop = new Properties();
            FileInputStream fis = new FileInputStream(".\\config.properties");
            prop.load(fis);

        } catch (FileNotFoundException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

四:读取完配置文件后,我们就应该来创建client对象,get/post对象和httpresponse对象(client-->看做postman),用来发送请求的对象,我们将get和post请求都封装到一个类中(老版本创建httpclient对象的时候,用的是

HttpClient httpClient = new DefaultHttpClient();

,但是这个方法已经差不多被弃用了,所以我们不用这个,我们用下面的方式)

package com.yufeng.httpclient.restclient;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
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 java.io.IOException;
import java.util.HashMap;

public class RestClient {
    //1. Get 请求方法

    public CloseableHttpResponse get(String url) throws IOException {

        //创建一个可关闭的HttpClient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        //创建一个HttpGet的请求对象
        HttpGet httpget = new HttpGet(url);
        //执行请求,相当于postman上点击发送按钮,然后赋值给HttpResponse对象接收
        CloseableHttpResponse httpResponse = httpclient.execute(httpget);
        return httpResponse;

    }

    //    2.POST请求方法
    public CloseableHttpResponse post(String url, HashMap<String, String> headermap, String entityString) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        //加载请求头到httppost对象
        for (HashMap.Entry<String, String> entry : headermap.entrySet()) {
            httpPost.addHeader(entry.getKey(), entry.getValue());
        }
//      设置playload
        httpPost.setEntity(new StringEntity(entityString));

        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
        return httpResponse;
    }
}

五:接下来如果我们只做get请求,那就在来一个测试类就行了(如果需要做响应断言,就自己写一个util类进行解析,后续会将该类的方法提供出来)

package com.yufeng.httpclient;

import com.yufeng.httpclient.base.TestBase;
import com.yufeng.httpclient.restclient.RestClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import java.io.IOException;

public class GetApiTest extends TestBase {
    TestBase testBase;
    String host;
    String url;
    RestClient restClient;
    CloseableHttpResponse closeableHttpResponse;


    @BeforeClass
    public void setUp() {
        testBase = new TestBase();
        host = prop.getProperty("HOST");
        url = host + "/api/users";
    }


    @Test
    public void getAPITest() throws IOException {
        restClient = new RestClient();
        closeableHttpResponse= restClient.get(url);

        //断言状态码是不是200
        int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
        Assert.assertEquals(statusCode,RESPNSE_STATUS_CODE_200,"response status code is not 200");
    }
}

这样一个get请求的接口就差不多了,我们来看看结果:

然后我们来试试POST请求,一般post请求的入参我们都写在一个JavaBean中,如下:

package com.yufeng.httpclient.bean;

public class UserInfo {
    private String email;
    private String password;

    public UserInfo(String email, String password) {
        super();
        this.email = email;
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

因为想到post返回的是json格式的,我们上面说了要写一个util类进行解析,如下(这段代码是copy别的大神的,直接拿来用就好了):

package com.yufeng.httpclient.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class TestUtil {
    /**
     * @param responseJson                        ,这个变量是拿到响应字符串通过json转换成json对象
     * @param jpath,这个jpath指的是用户想要查询json对象的值的路径写法 jpath写法举例:1) per_page  2)data[1]/first_name ,data是一个json数组,[1]表示索引
     *                                            /first_name 表示data数组下某一个元素下的json对象的名称为first_name
     * @return,返回first_name这个json对象名称对应的值
     */


    //1 json解析方法
    public static String getValueByJPath(JSONObject responseJson, String jpath) {

        Object obj = responseJson;

        for (String s : jpath.split("/")) {

            if (!s.isEmpty()) {

                if (!(s.contains("[") || s.contains("]"))) {

                    obj = ((JSONObject) obj).get(s);

                } else if (s.contains("[") || s.contains("]")) {

                    obj = ((JSONArray) ((JSONObject) obj).get(s.split("\\[")[0])).get(Integer.parseInt(s.split("\\[")[1].replaceAll("]", "")));

                }
            }
        }
        return obj.toString();
    }
}

然后我们去试一试这个post请求的情况:

package com.yufeng.httpclient;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yufeng.httpclient.base.TestBase;
import com.yufeng.httpclient.bean.UserInfo;
import com.yufeng.httpclient.restclient.RestClient;
import com.yufeng.httpclient.util.TestUtil;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import java.io.IOException;
import java.util.HashMap;

public class PostApiTest extends TestBase {
    TestBase testBase;
    String host;
    String url;
    RestClient restClient;
    CloseableHttpResponse closeableHttpResponse;

    @BeforeClass
    public void setUp() {
        testBase = new TestBase();
        host = prop.getProperty("HOST");
        url = host + "/api/login";
        System.out.println("接口地址:"+ url);
    }

    @Test
    public void postapitest() throws IOException {
        restClient = new RestClient();
        //2.准备请求头信息
        HashMap<String, String> headermap = new HashMap<String, String>();
        headermap.put("content-type", "application/json");
        //3.对象转换成Json字符串
        UserInfo userInfo = new UserInfo("peter@klaven", "cityslicka");
        String userJsonstring = JSON.toJSONString(userInfo);
        System.out.println("请求数据:"+userJsonstring);
        closeableHttpResponse = restClient.post(url, headermap, userJsonstring);
        //验证状态码是不是200
        int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
        Assert.assertEquals(statusCode, RESPNSE_STATUS_CODE_200, "status code is not 200");

        //断言响应json内容中token是不是期待结果
        String responseString = EntityUtils.toString(closeableHttpResponse.getEntity());
        JSONObject responseJson = JSON.parseObject(responseString);
        System.out.println("响应数据:"+responseJson);
        //System.out.println(responseString);
        String token = TestUtil.getValueByJPath(responseJson, "token");
        Assert.assertEquals(token, "QpwL5tke4Pnpja7X", "登录失败");

    }

}

这是post请求的执行代码,我们来看看结果:

 

请求成功!!!现在先记录一下使用Testng+HttpClient进行接口测试的方式,后续再加上log4j和Extentreports进行日志的打印和报告的优化~~

项目下载地址:https://pan.baidu.com/s/1GRVf0g4vRuEAvigyed4Jcg  提取码:573g

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章