接口测试 httpclient 接口测试学习&实践

雪怪 · 2016年04月09日 · 最后由 beiank 回复于 2016年09月09日 · 1492 次阅读

这周刚刚辞职,闲着的时候想起社区接口测试公开课上的使用 httpclient 进行接口测试,于是就边学边试着自己写一个工程,过段时间后找工作也多了一个选择←_←
另外因为还只是个半次品,之前没怎么研究过接口测试,只是按照自己的想法慢慢扩展功能,所以就只放主要的代码了

工程结构

│  
├─config
│      BaceConfig.java          //全局变量,定义域名之类的
│      MysqlMethod.java        //连接到数据库,执行查询语句
│      
├─httpclientUtil
│      JsonUtil.java          //读取本地文件、解析json机构
│      TestMethod.java          //get和post方法,打印返回结果
│      
└─inputFileManage
        Login.java                //执行Login模块的接口测试
        Main.java              //暂时放置着

本地输入的 json 文件

[
{
    "phone":"13*********",                                      //参数1
    "password":"******",                                          //参数2
    "type":1,                                                          //参数3
    "assertMethod":{    
        "ret":0                                                    //断言
    },
    "mysqlMethod":{
        "uid":"select uid from ****** where phone = 13*********"                          //数据校验
    }
},
{
    "phone":"18*********",
    "password":"******",
    "type":2,
    "assertMethod":{
        "ret":1
    },
    "mysqlMethod":{
        "uid":"select uid from ****** where phone = 13*********"
    }
}
]

部分代码

  • GET 方法

  • 执行 Login 部分测试

package inputFileManage;
import httpclientUtil.*;
import junit.framework.Assert;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.awt.List;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;

import com.fasterxml.jackson.annotation.JsonFormat.Value;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import config.BaceConfig;

public class Login {
    //全局配置
    private static String filePath = "D:/开发项目/eclipse/workspace/InterfaceTest/inputFile/login.json";
    private static String url = BaceConfig.baceUrl + "/account/login";
    private static int num = 3;
    private static String[] name = {"phone","password","type"};

    //json的参数
    private String phone;
    private String password;
    private int type;

    private AssertMethod assertMethod;
    private MysqlMethod mysqlMethod;

    //Assert
    public static class AssertMethod {
        private int ret;

        public int getRet() {
            return ret;
        }

        public void setRet(int ret) {
            this.ret = ret;
        }
    }

    //Mysql
    public static class MysqlMethod {
        private String uid;

        public String getUid() {
            return uid;
        }

        public void setUid(String uid) {
            this.uid = uid;
        }
    }

    //json参数的getters/setters方法
    public String getPhone() {
        return phone;
    }

    public String getPassword() {
        return password;
    }

    public int getType() {
        return type;
    }

    public AssertMethod getAssertMethod() {
        return assertMethod;
    }

    public MysqlMethod getMysqlMethod() {
        return mysqlMethod;
    }

    //全局配置的getters/setters方法
    public String getFilePath() {
        return filePath;
    }

    public String getUrl() {
        return url;
    }

    public int getNum() {
        return num;
    }

    public String[] getName() {
        return name;
    }

    /**
     * 使用json-lib解析json
     * @param args
     * @throws ClientProtocolException
     * @throws IOException
     */
/*  
 * json-lib的效率低下,改用jackson进行json的解析
 * 
    public static void main(String[] args) throws ClientProtocolException, IOException{
        JSONArray readJson = new JsonUtil().readJsonlib(name, num, filePath);
        for (int i = 0; i < readJson.size(); i++) {
            ArrayList<String> temp = new ArrayList<String>();
            JSONObject jsonObject = readJson.getJSONObject(i);
            for (int j = 0; j < num; j++) {
                temp.add(jsonObject.getString(name[j]));
            }
            String[] value = temp.toArray(new String[0]);
            new TestMethod().get(url, num, name, value);
        }
    }
*/

    /**
     * 使用jackson解析json文件
     * @param args
     * @throws IOException 
     * @throws JsonMappingException 
     * @throws JsonParseException 
     * @throws SQLException 
     */
    public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException, SQLException{
        ObjectMapper mapper = new ObjectMapper();

        Login[] logins = mapper.readValue(new File(filePath), Login[].class);

        for (Login login : logins) {
//          System.out.println("phone: " + login.getPhone());
//          System.out.println("password: " + login.getPassword());
//          System.out.println("type: " + login.getType());
//          System.out.println("Assert: ret = " + login.getAssertMethod().getRet());
//          System.out.println("Mysql:" + login.getMysqlMethod().getUid());
//          System.out.println();

            String[] value = {login.getPhone(),login.getPassword(),Integer.toString(login.getType())};
            String test = new TestMethod().get(url, name.length, name, value);

            Responses rpse = new Responses().responses(test);

            if (rpse.getRet() == login.getAssertMethod().getRet()) {
                System.out.println("Assert Success!");
            }
            else {
                System.out.println("Assert Error!");
            }
            if (new config.MysqlMethod().MysqlMethod(login.getMysqlMethod().getUid(), rpse.getDatas().getUid())) {
                System.out.println("Mysql Success!");
            }
            else {
                System.out.println("Mysql Error!");
            }
        }
    }

    //解析响应信息
    public static class Responses {
        private int ret;
        private String msg;
        public Datas getDatas() {
            return datas;
        }

        private Datas datas;

        public int getRet() {
            return ret;
        }

        public String getMsg() {
            return msg;
        }

        public static class Datas{
            @JsonProperty(value = "PHPSESSID")
            private String phpsessid;

            private String uid;
            private String type;
            private String password;
            public String getUid() {
                return uid;
            }
            public void setUid(String uid) {
                this.uid = uid;
            }
            public String getType() {
                return type;
            }
            public void setType(String type) {
                this.type = type;
            }
            public String getPassword() {
                return password;
            }
            public void setPassword(String password) {
                this.password = password;
            }

            @JsonProperty(value = "PHPSESSID")
            public String getPhpsessid() {
                return phpsessid;
            }
        }

        public Responses responses(String rps) throws JsonParseException, JsonMappingException, IOException{
            ObjectMapper mapper_rp = new ObjectMapper();

            Responses tem = mapper_rp.readValue(rps, Responses.class);

            return tem;
        }
    }
}

执行结果(TODO)

-----------------------URL-----------------------
http://****************/****/login?phone=13*********&password=*****&type=1
-----------------------Header-----------------------
Date: Sat, 09 Apr 2016 10:59:31 GMT
Server: Apache/2.4.6 (CentOS) PHP/5.4.16
X-Powered-By: PHP/5.4.16
Set-Cookie: PHPSESSID=**************; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Set-Cookie: PHPSESSID=*****************; path=/
Vary: Accept-Encoding
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: application/json;charset:utf-8
-----------------------Status Code-----------------------
Status Code: 200
-----------------------HttpEntity-----------------------
{"ret":0,"msg":"\u767b\u5f55\u6210\u529f","datas":{"uid":"********","type":"1","PHPSESSID":"*************","password":"********************"}}

Assert Success!
Mysql Success!

目前没想好是把结果写入表格,还是看看能不能搭上 jenkins 什么的。。

小结

社区的公开课还是挺有意义的,不知道该学什么的时候,跟着课程自己试试慢慢也就有点思路该做什么了
另外,辞职后休息、玩啊、休息、玩啊占了大部分时间,加上第一次接触接口测试,所以问题还是很多,eg 正则匹配什么的、接口传参时异常处理、提取代码中公共部分优化代码结构,测试结果展示什么的。。。
所以这次就当做是一次学习小结吧

共收到 13 条回复 时间 点赞

有学习,有感悟,希望 testerhome 这个舞台可以让你成为明星

雪怪 #12 · 2016年04月09日 Author

#1 楼 @lihuazhang 谢谢~现在已经都已经养成习惯每天上论坛看看了

坚持,分享是第一步~

加油~

PS:Java 有个 okhttpclient ,封装得比 httpclient 好一些,写起来没那么累。你有兴趣可以试试

#4 楼 @chenhengjie123 okhttpclient 用在 android 开发中比较多。

#3 楼 @monkey 嗯,也感谢公开课老师的分享,因此我才会有自己写写的想法
@chenhengjie123 谢谢~待会我去了解下 okhttpclient,之后试着改写下看看

#5 楼 @lihuazhang 嗯,对。写起来省力,对接口自动化而言基本够用了。

收藏起来学习,赞

你的检查点是直接查询数据库?

从登陆开始,赞赞的,加油继续分享,接口测试 分 android 和 pc 么?我一直以为都是 有个接口,然后传参检测返回数据,他们有不同吗?

雪怪 #10 · 2016年04月11日 Author

#9 楼 @lose 预想的是通过 assertMethod 和 mysqlMethod,断言和数据库校验数据 2 种方式

雪怪 #12 · 2016年04月11日 Author

#10 楼 @xiuqi PC 端没接触过,不大清楚有什么区别

在论坛可以看到很多,多泡泡论坛也不错!

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册