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/
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2020-05-08 pytest文档39-参数化(parametrize)结合allure.title()生成不同标题报告
2018-05-08 appium+python自动化41-切换webview时候报chromedriver版本问题
2018-05-08 appium+python自动化40-adb offline(5037端口被占)
2017-05-08 python接口自动化1-发送get请求