JAVA接口自动化框架5——完善post、get、put、delete等各种请求

本章主要介绍各种请求的编写,及测试类测试方法

一、各种请求的方法编写

package com.qa.restclient;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONObject;
import com.qa.utils.fatjson.FastjsonUtils;

/*
 * 1.实现get请求方法及带请求头信息,POST请求方法,PUT方法,DELETE方法
 * 2.一个是带请求头信息的POST请求方法
 * 3.获取响应状态码
 * 4.json内容解析
 */
public class RestClient {
    
    private static final Logger log = LoggerFactory.getLogger(RestClient.class);
    
    // get请求方法
    public static CloseableHttpResponse get(String url) throws ClientProtocolException, IOException {
        return get(url, null);
    }

    // Get 请求方法(带请求头信息)
    public static CloseableHttpResponse get(String url, Map headers)
            throws ClientProtocolException, IOException {
        // 创建一个可关闭的HttpClient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建一个HttpGet的请求对象
        HttpGet httpget = new HttpGet(url);
        // 加载请求头到httpget对象
        if (headers != null && headers.size() > 0) {
            for (Map.Entry entry : headers.entrySet()) {
                httpget.addHeader(entry.getKey(), entry.getValue());
            }
        }
        // 执行请求,相当于postman上点击发送按钮,然后赋值给HttpResponse对象接收
        CloseableHttpResponse httpResponse = httpclient.execute(httpget);

        return httpResponse;
    }
    
    
    //POST方法(如果不需要header可传入null),提交form表单(默认application/x-www-form-urlencoded)
    public static CloseableHttpResponse postForm(String url, Map params, Map headers)
            throws ClientProtocolException, IOException {
        // 设置请求头数据传输格式,使用表单提交的方式,postman中有写
        //headers.put("Content-Type","application/x-www-form-urlencoded");
        return post(url, null, params, headers);
    }

    //  POST方法,发送json格式(如果不需要header可传入null)
    public static CloseableHttpResponse postJson(String url, String jsonString, Map headers)
            throws ClientProtocolException, IOException {
        //准备请求头信息
        headers.put("Content-Type", "application/json");//postman中有写
        return post(url, jsonString, null, headers);
    }    
    
    
    // POST方法
    static CloseableHttpResponse post(String url, String jsonString, Map params, Map headers)
            throws ClientProtocolException, IOException {
        // 创建一个可关闭的HttpClient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建一个HttpPost的请求对象
        HttpPost httppost = new HttpPost(url);
        // 构造请求体,创建参数队列
        if(jsonString != null && !"".equals(jsonString)) {
            httppost.setEntity(new StringEntity(jsonString));
        } else {
            // 构造请求体,创建参数队列
            List nvps = new ArrayList();
            if (params != null && params.size() > 0) {
                for (Map.Entry entry : params.entrySet()) {
                    nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
            }
            httppost.setEntity(new UrlEncodedFormEntity(nvps));
        }

        // 加载请求头到httppost对象
        if (headers != null && headers.size() > 0) {
            for (Map.Entry entry : headers.entrySet()) {
                httppost.addHeader(entry.getKey(), entry.getValue());
            }
        }
        // 发送post请求
        CloseableHttpResponse httpResponse = httpclient.execute(httppost);
        return httpResponse;
    }    
    
    // 4. Put方法
    public static CloseableHttpResponse put(String url, Map params, Map headers)
            throws ClientProtocolException, IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPut httpput = new HttpPut(url);
        // 构造请求体,创建参数队列
        List nvps = new ArrayList();
        if (params != null && params.size() > 0) {
            for (Map.Entry entry : params.entrySet()) {
                nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }
        httpput.setEntity(new UrlEncodedFormEntity(nvps));

        // 加载请求头到httpput对象
        if (headers != null && headers.size() > 0) {
            for (Map.Entry entry : headers.entrySet()) {
                httpput.addHeader(entry.getKey(), entry.getValue());
            }
        }
        // 发送put请求
        CloseableHttpResponse httpResponse = httpclient.execute(httpput);
        return httpResponse;
    }

    // 5. Delete方法
    public static CloseableHttpResponse delete(String url) throws ClientProtocolException, IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpDelete httpdel = new HttpDelete(url);

        // 发送put请求
        CloseableHttpResponse httpResponse = httpclient.execute(httpdel);
        return httpResponse;
    }

    /**
     * 获取响应状态码,常用来和TestBase中定义的状态码常量去测试断言使用
     * @param response
     * @return 返回int类型状态码
     */
    public static int getStatusCode(CloseableHttpResponse response) {
        int statusCode = response.getStatusLine().getStatusCode();
        log.info("解析,得到响应状态码:" + statusCode);
        return statusCode;
    }

    /**把字符串转换为JSON对象,get取出【JSONObject.get("name")】
     * @param response,
     *            任何请求返回返回的响应对象 @return, 返回响应体的json格式对象,方便接下来对JSON对象内容解析
     *            接下来,一般会继续调用TestUtil类下的json解析方法得到某一个json对象的值
     * @throws ParseException
     * @throws IOException
     */
    public static JSONObject getResponseJson(CloseableHttpResponse response) throws ParseException, IOException {
        log.info("得到响应对象的String格式");
        String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
        JSONObject responseJsonObj = FastjsonUtils.toJsonObject(responseString);
        log.info("返回响应内容的JSON对象");
        return responseJsonObj;
    }
    
    /**
     * 把json字符串转换成指定类型的实体bean
     * get取出【user.getName()】
     */
    public static  T getResponseJson2Bean(CloseableHttpResponse response, Class clazz)
            throws ParseException, IOException {
        String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
        log.info("得到响应对象的String格式,数据为:" + responseString);
        T t = FastjsonUtils.toBean(responseString, clazz);
        log.info("返回响应的实体bean对象");
        return t;
    }

}

二、添加host1等信息

/**
 * 该类可以当成所有测试类的模板基类,其他需要测试的类继承该类
 * session,token等需要全局使用的均需要在此类中进行定义;若测试需要登录可在本类进行登录
 * @author jff
 * @date 2018年9月25日
 * @version V1.0.1
 */
public abstract class BaseApi {
    protected String host1;
    protected String hostManager;
    protected String url;
    protected String testCaseExcel;
    protected static String sessionKey;
    
    @BeforeClass
    public void setUp() {
        host1=PropertiesUtils.getConfigValue("HOST");
        hostManager=PropertiesUtils.getConfigValue("HOSTMANAGER");
        testCaseExcel=PropertiesUtils.getConfigValue("TESTCASEDATE");
        
    }

config.properties中添加HOST

HOST=https://reqres.in

HOSTMANAGER=http://m.test.mwpark.cn

TESTCASEDATE = F:\\testCase1data.xlsx

三、测试类编写

1.delete请求测试编写

package tests;

import java.io.IOException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.log4j.Logger;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.qa.base.BaseApi;
import com.qa.base.Constants;
import com.qa.restclient.RestClient;

public class DeleteTest extends BaseApi{
    private  final static  Logger Log=Logger.getLogger(DeleteTest.class);
    
    @Test
    public void putTest() throws ClientProtocolException, IOException{
        String url = host1 + "/api/users/2";
        CloseableHttpResponse closeableHttpResponse=RestClient.delete(url);
        int statusCode=RestClient.getStatusCode(closeableHttpResponse);
        Assert.assertEquals(statusCode, Constants.RESPNSE_STATUS_CODE_204,"statusCode not 204");
        
    }
}

2. get请求测试类编写
 

package tests;
import java.io.IOException;

import org.apache.http.ParseException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.qa.base.BaseApi;
import com.qa.base.Constants;
import com.qa.restclient.RestClient;

public class GetTest extends BaseApi{
    private final static Logger log =Logger.getLogger(GetTest.class);
    /**
     * 无请求头
     * @throws IOException 
     * @throws ParseException 
     */
    @Test
    public void getTest() throws Exception{
        String url=host1+"/api/users?page=2";
        CloseableHttpResponse closeableHttpResponse=RestClient.get(url);
        //获得响应字符串,把响应实体转换成string字符串
        String responceString=EntityUtils.toString(closeableHttpResponse.getEntity());
        log.info("*************"+responceString);
        
        //从返回结果中获取状态码
        int statusCode = RestClient.getStatusCode(closeableHttpResponse);
        Assert.assertEquals(statusCode,Constants.RESPNSE_STATUS_CODE_200,"status code is not 200");
    }
}

3. put请求测试类编写

这个接口我要重建一个参数类,因为之前的那个不支持put

package com.qa.parameters;
/*
 * post请求需要传递的参数对象,相当于javabena
 * 添加有参构造和无参构造,添加set和get方法
 * */
public class Users {
    private String name;
    private String job;
    public Users() {
        super();
    }
    public Users(String name,String job) {
        super();
        this.job=job;
        this.name=name;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getJob() {
        return job;
    }
    public void setJob(String job) {
        this.job = job;
    }
}

 

测试编写
 

package tests;
import java.io.IOException;
import java.util.Map;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.alibaba.fastjson.JSONObject;
import com.qa.base.BaseApi;
import com.qa.parameters.Users;
import com.qa.restclient.RestClient;
import com.qa.utils.fatjson.FastjsonUtils;

public class PutTest extends BaseApi{
    private final static Logger log=Logger.getLogger(PutTest.class);
    
    @Test
    public void putTest() throws ClientProtocolException, IOException{
        String url=host1+"/api/users/2";
        Users user=new Users("jff","testers");
        Map mapparams =FastjsonUtils.toMap(FastjsonUtils.toJson(user));
        CloseableHttpResponse closeableHttpResponse=RestClient.put(url, mapparams, null);
        
        int statusCode=RestClient.getStatusCode(closeableHttpResponse);
        Assert.assertEquals(statusCode, 200);
        
        String responseString = EntityUtils.toString(closeableHttpResponse.getEntity());
        log.info("*************响应字符串为"+responseString);
        JSONObject jsonObject=FastjsonUtils.toJsonObject(responseString);
        String name= jsonObject.getString("name");
        String job=jsonObject.getString("job");
        Assert.assertEquals(name,"jff" ,"name is not jff");
        Assert.assertEquals(job,"testers" ,"job is not testers");
    }
}

5. post请求类编写(Form表单提交,Content-Type=application/x-www-form-urlencoded)

@Test
    public void postByFormTest() throws ClientProtocolException, IOException{
        String url=hostManager+"/parkingManager/applogin/loginIn";
        Manager manager = new Manager("yanczapp","8ddcff3a80f4189ca1c9d4d902c3c909","0571001");
        Map map=FastjsonUtils.toMap(FastjsonUtils.toJson(manager));
        Log.info("my out**********"+map);
        CloseableHttpResponse closeableHttpResponse = RestClient.postForm(url, map, null);
        
        //断言状态码是不是200
        int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
        Assert.assertEquals(statusCode,Constants.RESPNSE_STATUS_CODE_200,"status code is not 200");
    
        //断言响应是不是期待结果
        String responseString = EntityUtils.toString(closeableHttpResponse.getEntity());
        Log.info("my out**********"+responseString);
        JSONObject res  = FastjsonUtils.toJsonObject(responseString);
        sessionKey = FastjsonUtils.toMap(res.getString("data")).get("session_key");
        Log.info("data**********: " + res.getString("message"));
        Log.info("data**********: " + sessionKey);
        
        String account=FastjsonUtils.toMap(res.getString("data")).get("account");
        Assert.assertEquals(account,"yanczapp" ,"account code is not error");
    }

6. post请求类编写(json格式,Content-Type=application/json)
 

package tests;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.alibaba.fastjson.JSONObject;
import com.qa.base.BaseApi;
import com.qa.parameters.Users;
import com.qa.restclient.RestClient;
import com.qa.utils.fatjson.FastjsonUtils;

public class PostTest extends BaseApi{
    private final static Logger log=Logger.getLogger(PostTest.class);
    
    @Test
    public void postByJsonTest() throws Exception, IOException{
        String url=host1+"/api/users";
        Users users=new Users("jiangfeifei","tester");
        String userParams=FastjsonUtils.toJson(users);
        //***如果在resetClient方法中邪了header,那测试类就必须传入header
        Map header=new HashMap();
        header.put("Content-Type", "application/json");
        CloseableHttpResponse closeableHttpResponse=RestClient.postJson(url, userParams, header);
        String respS=EntityUtils.toString(closeableHttpResponse.getEntity());
        log.info("********响应为"+respS);
        
        int statusCode=RestClient.getStatusCode(closeableHttpResponse);
        Assert.assertEquals(statusCode, 201);
        
        JSONObject jsonObject=FastjsonUtils.toJsonObject(respS);
        String name=jsonObject.getString("name");
        String job=jsonObject.getString("job");
        
        Assert.assertEquals(name, "jiangfeifei");
        Assert.assertEquals(job, "tester");
    }
}

 

没有测试的测试类

@Test
	//post中json提交Content-Type=application/json
	public void loginManagerAppByJson() throws ClientProtocolException, IOException{
		String url=hostManager+"/parkingManager/applogin/loginIn";
		Manager manager = new Manager("yanczapp","8ddcff3a80f4189ca1c9d4d902c3c909","0571001");
		String json = FastjsonUtils.toJson(manager);
		Log.info("my out**********"+json);
		CloseableHttpResponse closeableHttpResponse = RestClient.postJson(url, json, null);
		//断言状态码是不是200
		int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
		Assert.assertEquals(statusCode,Constants.RESPNSE_STATUS_CODE_200,"status code is not 200");
	
		//断言响应是不是期待结果
		String responseString = EntityUtils.toString(closeableHttpResponse.getEntity());
		Log.info("my out**********"+responseString);
		res = FastjsonUtils.toJsonObject(responseString);
		sessionKey = FastjsonUtils.toMap(res.getString("data")).get("session_key");
		Log.info("data**********: " + res.getString("message"));
		Log.info("data**********: " + sessionKey);
		
		String account=FastjsonUtils.toMap(res.getString("data")).get("account");
		Assert.assertEquals(account,"yanczapp" ,"account code is not error");
	}

 

你可能感兴趣的:(JAVA接口自动化测试框架)