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

前言

一个完整的接口测试,包括:请求>获取响应正文>断言。所谓断言,就是结果和预期对比,如果一致,则用例通过,如果不一致,断言失败,用例执行失败。

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

Tests编写

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

常用断言方法

Setting an environment variable :设置一个环境变量

pm.environment.set("variable_key", "variable_value");

Getting an environment variable : 获取环境变量

pm.environment.get("variable_key");

Set a global variable :设置一个全局变量

pm.globals.set("variable_key", "variable_value");

Check if response body contains a string : 检查响应主体是否包含字符串

pm.test("Body matches string", function () {    pm.expect(pm.response.text()).to.include("string_you_want_to_search");});

Check for a JSON value :检查JSON值

pm.test("Your test name", function () {var jsonData = pm.response.json();    pm.expect(jsonData.value).to.eql(100);});

Response time is less than 200ms :响应时间小于200ms

pm.test("Response time is less than 200ms", function () {    pm.expect(pm.response.responseTime).to.be.below(200);});

校验返回的 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 方式对提取的返回结果校验

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


//校验message为OK
pm.test("response msg is ok", function () {
    pm.expect(pm.response.json().message).to.equal("ok");
});

 

 校验状态码和返回头部及头部参数

 校验返回状态码是200,校验 Content-Type 在返回头部,校验返回的头部Content-Type 值为 application/json

pm.test("Status test", function () {
    pm.response.to.have.status(200);
});

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

pm.test("Content-Type header is application/json", () => {
  pm.expect(pm.response.headers.get('Content-Type')).to.eql('application/json');
});

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝娃不蓝

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值