目录
从基础到高级一共分为 5 大类:状态码、响应体、字段值、性能、链式依赖,覆盖 95% 的实际测试场景。
一、基础断言(状态码、响应类型等)
// 1. 状态码为 200
pm.test("状态码应为 200", function () {
pm.response.to.have.status(200);
});
// 2. 状态码属于 2xx 成功范围
pm.test("状态码应为 2xx", function () {
pm.expect(pm.response.code).to.be.within(200, 299);
});
// 3. Content-Type 应为 JSON
pm.test("响应类型应为 JSON", function () {
pm.response.to.have.header("Content-Type");
pm.expect(pm.response.headers.get("Content-Type")).to.include("application/json");
});
// 4. 响应时间应小于 500ms
pm.test("响应时间应小于 500ms", function () {
pm.expect(pm.response.responseTime).to.be.below(500);
});
用途:快速判断接口是否正常响应、性能是否达标。
二、响应体结构验证(JSON 字段检查)
// 5. 响应体中必须包含某字段
pm.test("响应体包含字段 'data'", function () {
const jsonData = pm.response.json();
pm.expect(jsonData).to.have.property("data");
});
// 6. 嵌套字段不为空
pm.test("用户信息应存在且不为空", function () {
const jsonData = pm.response.json();
pm.expect(jsonData.user).to.exist;
pm.expect(jsonData.user.name).to.be.a("string").and.not.empty;
});
// 7. 数组长度验证
pm.test("返回的列表至少有 1 条数据", function () {
const jsonData = pm.response.json();
pm.expect(jsonData.list).to.be.an("array").that.is.not.empty;
});
// 8. 校验返回数据类型
pm.test("价格字段应为数字类型", function () {
const jsonData = pm.response.json();
pm.expect(jsonData.price).to.be.a("number");
});
用途:确保返回数据结构正确,防止后端字段丢失或类型错误。

最低0.47元/天 解锁文章
614

被折叠的 条评论
为什么被折叠?



