• 8-5接口测试用例设计与编写-3发送消息与图片


    1. 获取token

    public class WXopenDemo {
        /**
         * 异常测试:错误的参数
         */
        @Test(groups = "testtoken")
        public void getToken1(){
            String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";
            String corpid = "123456";
            String corpsecret = "123456";
            given().param("corpid",corpid).param("corpsecret",corpsecret).get(url).then().body("errcode",equalTo(40013));//prettyPeek连带消息头一起打印
    
        }
        /**
         * 获取token
         */
        @Test(groups = "testtoken")
        public void getToken2(){
            String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";
            String corpid = "XXXXXXXXXXXX";
            String corpsecret = "XXXXXXXXXXXXX";
            given().param("corpid",corpid).param("corpsecret",corpsecret).get(url).then().statusCode(equalTo(200));//prettyPeek连带消息头一起打印
        }
    }
    

    使用xml组织用例,并运行

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
    <suite name="All Test Suite" verbose="1">
        <test verbose="2" preserve-order="true" name="lesson1"><!--测试名称-->
            <groups>
                <run>
                    <include name="testtoken" /><!--只跑add组-->
                </run>
            </groups>
            <classes>
                <class name="com.csj2018.WXopenDemo" />
            </classes>
        </test>
    </suite>
    

    2. 发送消息

    2.1 发送文本消息

        /**
         * 发消息 
         */
        @Test
        public void sendMessage(){
            String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";
            //先获取token
            String corpid = "XXXXXXXXXXXX";
            String corpsecret = "XXXXXXXXX";
            Response res = given().param("corpid",corpid).param("corpsecret",corpsecret).get(url).prettyPeek();
            assertThat(res.statusCode(),equalTo(200));
            String accessToken = res.getBody().jsonPath().getString("access_token");
            assertThat(accessToken,notNullValue());
            //发送消息
            String messageUrl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+accessToken;
            String reqContent = "{
    " +
                    "   "toparty" : "4",
    " +
                    "   "msgtype" : "text",
    " +
                    "   "agentid" : 1000004,
    " +
                    "   "text" : {
    " +
                    "       "content" : "你的快递已到,请携带工卡前往邮件中心领取。\n出发前可查看<a href=\"http://work.weixin.qq.com\">邮件中心视频实况</a>,聪明避开排队。"
    " +
                    "   },
    " +
                    "   "safe":0,
    " +
                    "   "enable_id_trans": 0
    " +
                    "}";
            given().contentType(ContentType.JSON).body(reqContent).post(messageUrl).prettyPeek().then().body("errmsg",equalTo("ok"));
        }
    

    2.2 优化代码:将重复代码封装为工具类,将请求封装为一个对象,便于重复使用,提高易读性

    package com.csj2018.utils;
    
    import io.restassured.response.Response;
    
    import java.io.File;
    
    import static io.restassured.RestAssured.given;
    import static org.hamcrest.CoreMatchers.equalTo;
    import static org.hamcrest.CoreMatchers.notNullValue;
    import static org.junit.Assert.assertThat;
    
    public class WXUtils {
        private static String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";
        private static String corpid = "XXXXXXXXXX";
        private static String corpsecret = "XXXXXXXXXXXXXXXXX";
        private static String uploadImageUrl= "https://qyapi.weixin.qq.com/cgi-bin/media/upload";
    
        public static String getToken(){
            Response res = given().param("corpid",corpid).param("corpsecret",corpsecret).get(url).prettyPeek();
            assertThat(res.statusCode(),equalTo(200));
            String accessToken = res.getBody().jsonPath().getString("access_token");
            assertThat(accessToken,notNullValue());
            return accessToken;
        }
    }
    

    请求参数类

    package com.csj2018.model;
    
    import java.util.Map;
    
    public class WXTextMessageModel {
        /**
         * {
         *    "touser" : "UserID1|UserID2|UserID3",
         *    "toparty" : "PartyID1|PartyID2",
         *    "totag" : "TagID1 | TagID2",
         *    "msgtype" : "text",
         *    "agentid" : 1,
         *    "text" : {
         *        "content" : "你的快递已到,请携带工卡前往邮件中心领取。
    出发前可查看<a href="http://work.weixin.qq.com">邮件中心视频实况</a>,聪明避开排队。"
         *    },
         *    "safe":0,
         *    "enable_id_trans": 0
         * }
         */
        private String touser;
        private String toparty;
        private String totag;
        private String msgtype;
        private Integer agentid;
        private Map<String, String> text;
        private Map<String, String> image;
        private Integer safe;
        private Integer enable_id_trans;
        //省略getter和setter方法 mac快捷键ctrl + enter
    
        /**
         * 发送文本
         */
        @Test
        public void sendMessage2(){
            String accessToken = WXUtils.getToken();
            //发送消息
            String messageUrl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+accessToken;
            WXTextMessageModel wxTextMessageModel = new WXTextMessageModel();
            wxTextMessageModel.setToparty("4");
            wxTextMessageModel.setMsgtype("text");
            wxTextMessageModel.setAgentid(1234567);
            Map<String, String> map = new HashMap<>();
            map.put("content","你的快递已到,请携带工卡前往邮件中心领取。\n出发前可查看<a href=\"http://work.weixin.qq.com\">邮件中心视频实况</a>,聪明避开排队。");
            wxTextMessageModel.setText(map);
            wxTextMessageModel.setSafe(0);
            wxTextMessageModel.setEnable_id_trans(0);
    
            given().contentType(ContentType.JSON).body(wxTextMessageModel).post(messageUrl).prettyPeek().then().body("errmsg",equalTo("ok"));
            //如果报错cannot serialize object because no JSON serializer fount in classpath.Please put either Jackson(Databind) or Gson in the classpath.可能是json-schema-validator缺失,倒入即可
        }
    

    2.3 发送图片

    • 1.发送图片需要从上传临时素材接口获取media_id
    • 2.上传图片需要文件标识名
    • 3.去rest-assured查找使用说明

      上传临时素材的接口

      Multi-part form data示例
    • 1.在工具类中先按示例中上传文件到临时素材接口
      WXUtils.java
        public static String getWXMediaId(){
            String accessToken = getToken();
            System.out.println(accessToken);
            Response res = given().contentType("multipart/form-data")
                    .queryParam("access_token",accessToken)
                    .queryParam("type","image")
                    .multiPart("meida",new File("src/test/image/singleDog.jpg")).when().post(uploadImageUrl).prettyPeek();
            String mediaId = res.getBody().jsonPath().getString("media_id");
            System.out.println(32+mediaId);
            assertThat(mediaId,notNullValue());
            return mediaId;
        }
    
    • 编写发送图片的用例
        /**
         * 发送图片
         */
        @Test
        public void sendImage(){
    
            //发送消息
            String messageUrl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+WXUtils.getToken();
            WXTextMessageModel wxTextMessageModel = new WXTextMessageModel();
            wxTextMessageModel.setToparty("4");
            wxTextMessageModel.setMsgtype("image");
            wxTextMessageModel.setAgentid(1000004);
            Map<String, String> imageMap = new HashMap<>();
            imageMap.put("media_id",WXUtils.getWXMediaId());
            wxTextMessageModel.setImage(imageMap);
            wxTextMessageModel.setSafe(0);
            wxTextMessageModel.setEnable_id_trans(0);
    
            given().contentType(ContentType.JSON).body(wxTextMessageModel).post(messageUrl).prettyPeek().then().body("errmsg",equalTo("ok"));
        }
    

    3.我司上传接口

    现在公司业务很大比例外包出去,合作伙伴没有提供接口文档,swagger的描述也不够清晰。因为懒,我会等踩着客户端的肩膀写接口用例。
    分析header,对我有价值的只有Content-Type为multipart/form-data

    再分析Multipart,此处有2点:

    • resultType为0
    • 上传文件名为fileContent,类型为image/jpg
    public class TestUploadFile extends BaseInfo {
        String url = "*****/uploadFile";
        @Test
        public void sendPost(){
            System.out.println(url);
            try {
                Response res = given()
                        .header("Content-Type","multipart/form-data")
                        .header("accept", "application/json;charset=UTF-8")
                        .multiPart("resultType",0)
                        .multiPart("fileContent",new File("/Users/chenshanju/Desktop/1th/lc76.jpeg"),"image/jpg")
                        .post(url)
                        .prettyPeek();
                String imgId = res.jsonPath().get("result[0]");
                System.out.println(imgId);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
    

    4.其他:

    1. print和prettyPeek的区别

    print只打印响应体;prettyPeek会讲响应头和响应体一起打印

    2. queryParam和param的区别

    param用于get请求中;
    queryParam和formParam用于post请求中,queryParam用于拼接URL,formParam用于提交表单
    使用body传递参数,可以指定编码,如contentType("application/json; charset=UTF-16")

    Message message = new Message();
    message.setMessage("My messagee");
    given().
           contentType("application/json").
           body(message).
    when().
          post("/message");
    

    使用formParam传递参数

    Message message = new Message();
    message.setMessage("My messagee");
    given().
           contentType("application/json; charset=UTF-16").
           formParam("param1", message).
    when().
          post("/message");
    

    更多查看testerhome rest-assured使用指南github

  • 相关阅读:
    centos 7 搭建 LNMP ( Linux+Nginx+MySQL+PHP )
    centos 7 安装 redis-5.0.5
    centos 7 安装 Oracle 12c
    centos 7 SVN安装脚本搭建主从同步灵活切换
    Windwos Java‘bat 环境变量配置脚本
    centso 7 Keepalived 配置脚本
    centos 7 私有云盘 OwnCloud 安装搭建脚本
    Linux fing cd 查找文件/文件夹并进入目录命令
    Linux grep命令 -- 三剑客老三
    基础脚本
  • 原文地址:https://www.cnblogs.com/csj2018/p/11664843.html
Copyright © 2020-2023  润新知