小言_互联网的博客

详解Postman校验响应数据之设置断言编写Test脚本

226人阅读  评论(0)

前言

通常在我们做接口测试的时候,我们是不是需要去看接口的响应数据是否与我们期望的值相匹配。Postmna 就提供了这个功能,我们可以使用 JavaScript 为 Postman API 请求编写 Tests 脚本。

那么我们以登录的接口为例

接口响应的数据为:

{
   
    "code": 200,
    "data": {
   
        "firstLogin": true,
        "token": "b2d08847c393f7f15b654f54bebdc0d2ce72b3d3",
        "userBizInfoEntity": {
   
            "accountType": 0,
            "adSource": "",
            "bizType": 1,
            "deleteFlag": false,
            "gmtCreated": 1612357476000,
            "gmtModified": 1621236421000,
            "marketChannel": "weixin",
            "mobile": "188****7063",
            "nickname": "七月",
            "openid": "",
            "subBizType": 101,
            "unionid": "",
            "userIcon": "https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTLvS7ic5AxAmyFVpz2Mku861brOVUEV1pibhIK38MzY0CHIWAEWf1wNkia67qcQfkCkDrXUoYoVlkIVQ/132",
            "userId": 3000010823,
            "userStatus": 0,
            "username": "fg3000010822"
        }
    },
    "success": true,
    "traceId": "9692c9d8a7124b79"
}

校验返回的 body 是 json 格式

pm.test("response must be valid and have a body", function () {
   
     pm.response.to.be.ok;
     pm.response.to.be.withBody;
     pm.response.to.be.json;
});

我们输入测试脚本,运行后可以看到接口返回TestResults位置显示PASS,说明此校验通过


校验body具体内容

// 校验code为200
pm.test("response code must to be 200", function () {
   
    pm.expect(pm.response.json().code).to.equal(200);
});

//校验 success 为 true!
pm.test("response msg must to be login success!", function () {
   
    pm.expect(pm.response.json().success).to.equal(true);
});

//校验token 长度为40位
pm.test("response token length must to be 40", function () {
   
    pm.expect(pm.response.json().data.token).to.lengthOf(40);
});


校验状态码


// 校验状态码
pm.test("Status test", function () {
   
    pm.response.to.have.status(200);
});

校验返回头部参数


// 校验 Content-Type 在返回头部

pm.test("Content-Type header is present", () => {
   
  pm.response.to.have.header("Content-Type");
});


// 校验返回的头部Content-Type 值为 application/json
pm.test("Content-Type header is application/json", () => {
   
  pm.expect(pm.response.headers.get('Content-Type')).to.eql('application/json');
});


断言返回值与变量相等

比如我们这边将登录的账号设置为全局变量,然后我们需要校验设置的全局变量是否和接口返回的手机号码相同,我们可以通过如下代码进行判断

// 校验全局变量是否与响应数据相同
pm.test("Response property matches environment variable", function () {
   
  pm.expect(pm.response.json().data.mobile).to.eql(pm.environment.get("username"));
});



转载:https://blog.csdn.net/weixin_43865008/article/details/116936458
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场