• postman使用教程8-设置断言(Tests脚本编写)


    前言

    当一个接口发送请求有返回结果后,如何知道返回的结果符合预期?可以在 postman 里面的 Tests 写脚本断言符合结果符合预期。
    Tests 是接口返回 response 之后的脚本操作,可以使用 JavaScript 为 Postman API 请求编写 Tests 脚本。

    Tests编写

    Tests 可以添加到单个请求,文件夹和集合中,这里以单个请求为例。

    登陆接口返回

    {
        "code": 0,
        "msg": "login success!",
        "username": "test",
        "token": "580406b0df935496f96313fc98ae7e18d39d62af"
    }
    

    校验返回的 body 是 json 格式

    首先可以校验返回的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具体内容

    上面是直接pm.response.to.be方式对response对象校验的,也可以用pm.expect(actual_result).to 方式对提取的返回结果校验

    # 作者-上海悠悠 QQ交流群:717225969
    # blog地址 https://www.cnblogs.com/yoyoketang/
    
    
    // 校验code为0
    pm.test("response code must to be 0", function () {
        pm.expect(pm.response.json().code).to.equal(0);
    });
    
    //校验msg 为 login success!
    pm.test("response msg must to be login success!", function () {
        pm.expect(pm.response.json().msg).to.equal("login success!");
    });
    
    //校验token 长度为40位
    pm.test("response token length must to be 40", function () {
        pm.expect(pm.response.json().token).to.lengthOf(40);
    });
    

    校验状态码和返回头部

    校验返回状态码是200

    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');
    });
    

    断言返回值与变量相等

    如果我前面登陆的body参数引用了环境变量username

    接口返回的json数据又有这个账号名称,想断言结果返回的值和变量username相等,于是可以先获取环境变量值

    pm.environment.get("name");
    

    于是脚本这样写

    pm.test("Response property matches environment variable", function () {
      pm.expect(pm.response.json().username).to.eql(pm.environment.get("username"));
    });
    

    作者-上海悠悠 blog地址 https://www.cnblogs.com/yoyoketang/

  • 相关阅读:
    【PaddlePaddle系列】Executor逐步训练模型
    【PaddlePaddle】自然语言处理:句词预测
    【PaddlePaddle系列】CIFAR-10图像分类
    【图像处理】灰度图、亮度峰值极值查找
    【PaddlePaddle系列】报错解决方法合集 (不定时更新)
    【PaddlePaddle系列】手写数字识别
    Thymeleaf 基本用法总结
    Eclipse+Marven + spring mvc 新建一个 Hello world 项目
    Java EE 开发环境搭建
    vue.js安装过程(npm安装)
  • 原文地址:https://www.cnblogs.com/yoyoketang/p/14746882.html
Copyright © 2020-2023  润新知