Java自动化测试(接口操作优化 15)

时间:2022-07-22
本文章向大家介绍Java自动化测试(接口操作优化 15),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

设置头部部分代码提取

由于发起post请求的时候,它可能为json格式,也可能为form表单格式。所以对他进行提取

public static void post(String url, String params, Map<String, String> headers) throws Exception {
    HttpPost post = new HttpPost(url);
    setHeaders(headers, post);
    StringEntity body = new StringEntity(params, "utf-8");
    post.setEntity(body);
    HttpClient client = HttpClients.createDefault();
    HttpResponse response = client.execute(post);
    printResponse(response);
}

接收一个Map<String, String> headers

遍历这个Map对象,将它一个个通过setHeader写入到headers中

/**
 * 设置请求头
 *
 * @param headers 包含了请求头的Map集合
 * @param request 请求类型
 */
private static void setHeaders(Map<String, String> headers, HttpRequest request) {
    Set<String> keySet = headers.keySet();
    for (String key : keySet) {
        request.setHeader(key, headers.get(key));
    }
}

测试代码修改

@Test(dataProvider = "datas")
public void test(CaseInfo caseInfo) {
    try {
        HashMap<String, String> headers = new HashMap<>();
        headers.put("X-Lemonban-Media-Type", "lemonban.v1");
        String contentType = caseInfo.getContentType();
        if ("json".equals(contentType)) {
            headers.put("Content-Type", "application/json");
        } else if ("form".equals(contentType)) {
            headers.put("Content-Type", "application/x-www-form-urlencoded");
        }
        if ("post".equals(caseInfo.getMethod())) {
            HttpUtils.post(caseInfo.getUrl(), caseInfo.getParams(), headers);
        } else if ("get".equals(caseInfo.getMethod())) {
            HttpUtils.get(caseInfo.getUrl(), headers);
        } else if ("patch".equals(caseInfo.getMethod())) {
            HttpUtils.patch(caseInfo.getUrl(), caseInfo.getParams(), headers);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

修改headers代码:

HashMap<String, String> headers = new HashMap<>();
headers.put("X-Lemonban-Media-Type", "lemonban.v1");
String contentType = caseInfo.getContentType();
if ("json".equals(contentType)) {
    headers.put("Content-Type", "application/json");
} else if ("form".equals(contentType)) {
    headers.put("Content-Type", "application/x-www-form-urlencoded");
}

先定义了一个空的HashMap

然后根据测试数据,往它里面插入头部信息。

修改form

当传入的内容是json格式,但是传入方式为form的时候,会出现异常。需要将json转换为form格式

if ("json".equals(contentType)) {
    headers.put("Content-Type", "application/json");
} else if ("form".equals(contentType)) {
    Map<String, String> map = JSONObject.parseObject(params, Map.class);
    String formParams = "";
    for (String key : map.keySet()) {
        formParams += key + "=" + map.get(key) + "&";
    }
    params = formParams.substring(0, formParams.length() - 1);
    headers.put("Content-Type", "application/x-www-form-urlencoded");
}

代码提取

将整个操作提取为一个call函数

public static void call(CaseInfo caseInfo) {
    try {
        HashMap<String, String> headers = new HashMap<>();
        headers.put("X-Lemonban-Media-Type", "lemonban.v1");

        String params = caseInfo.getParams();
        String url = caseInfo.getUrl();
        String method = caseInfo.getMethod();
        String contentType = caseInfo.getContentType();

        if ("json".equals(contentType)) {
            headers.put("Content-Type", "application/json");
        } else if ("form".equals(contentType)) {
            params = jsonStr2KeyValueStr(params);
            headers.put("Content-Type", "application/x-www-form-urlencoded");
        }

        if ("post".equals(method)) {
            HttpUtils.post(url, params, headers);
        } else if ("get".equals(method)) {
            HttpUtils.get(url, headers);
        } else if ("patch".equals(method)) {
            HttpUtils.patch(url, params, headers);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

/**
 * json字符串转换成key=value
 * 例如:{"mobilephone":"13877788811","pwd":"12345678"} => mobilephone=13877788811&pwd=12345678
 *
 * @param json Json字符串
 * @return
 */
private static String jsonStr2KeyValueStr(String json) {
    Map<String, String> map = JSONObject.parseObject(json, Map.class);
    String formParams = "";
    for (String key : map.keySet()) {
        formParams += key + "=" + map.get(key) + "&";
    }
    return formParams.substring(0, formParams.length() - 1);
}

后续测试部分代码为:

@Test(dataProvider = "datas")
public void test(CaseInfo caseInfo) {
    HttpUtils.call(caseInfo);
}

登陆接口测试

测试数据: https://github.com/zx490336534/auto_api/blob/master/src/test/resources/cases_v3.xlsx

同理登陆接口测试 只需修改测试数据即可

DataProvider中修改

List list = ExcelUtils.read(1, 1, CaseInfo.class);
package com.zhongxin.cases;

import com.zhongxin.pojo.CaseInfo;
import com.zhongxin.utils.ExcelUtils;
import com.zhongxin.utils.HttpUtils;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import java.util.List;

public class LoginCase {
    @Test(dataProvider = "datas")
    public void test(CaseInfo caseInfo) {
        HttpUtils.call(caseInfo);
    }

    @DataProvider
    public Object[] datas() {
        List list = ExcelUtils.read(1, 1, CaseInfo.class);
        return list.toArray();
    }
}