You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写Postman if/else语句实现响应Schema条件分支校验

Postman 响应Schema分支校验改造方案

原脚本问题说明

  • 旧脚本未做响应场景判断,会无差别执行全部6种场景的JSON Schema校验
  • 每次接口请求仅会返回1种状态场景,因此运行结果永远是1条校验通过、其余5条全部失败,结果冗余无实际参考价值

改造思路

先提取接口实际返回的HTTP状态码、响应体内容,通过if-else分支匹配对应场景的Schema规则,仅执行当前响应对应的单条校验;同状态码下的细分错误场景通过响应报文特征做二次区分,未覆盖的状态码直接抛出明确提示。

改造后完整脚本

// 从集合变量读取所有预定义的响应Schema
const schema201PostSuccess = pm.collectionVariables.get("schema201PostSuccess");
const schema400BmcIdFail = pm.collectionVariables.get("schema400BmcIdFail");
const schema401Unauthorized = pm.collectionVariables.get("schema401Unauthorized");
const schema400BadRequest = pm.collectionVariables.get("schema400BadRequest");
const schema404InsufficientPermission = pm.collectionVariables.get("schema404InsufficientPermission");
const schema500InternalServerError = pm.collectionVariables.get("schema500InternalServerError");

// 获取当前接口实际返回的状态码与响应体
const responseCode = pm.response.code;
const responseData = pm.response.json();

if (responseCode === 201) {
    pm.test("愿望单记录创建成功,响应Schema校验通过", function () {
        pm.response.to.have.jsonSchema(schema201PostSuccess);
    });
} else if (responseCode === 400) {
    // 区分bmc_id参数错误、通用请求错误两种400场景
    if (responseData && responseData.message && responseData.message.includes("bmc_id")) {
        pm.test("bmc_id参数非法场景响应Schema校验通过", function () {
            pm.response.to.have.jsonSchema(schema400BmcIdFail);
        });
    } else {
        pm.test("通用400请求错误场景响应Schema校验通过", function () {
            pm.response.to.have.jsonSchema(schema400BadRequest);
        });
    }
} else if (responseCode === 401) {
    pm.test("未授权访问场景响应Schema校验通过", function () {
        pm.response.to.have.jsonSchema(schema401Unauthorized);
    });
} else if (responseCode === 404) {
    pm.test("权限不足场景响应Schema校验通过", function () {
        pm.response.to.have.jsonSchema(schema404InsufficientPermission);
    });
} else if (responseCode === 500) {
    pm.test("服务内部错误场景响应Schema校验通过", function () {
        pm.response.to.have.jsonSchema(schema500InternalServerError);
    });
} else {
    pm.test("响应状态码未覆盖校验规则", function () {
        throw new Error(`当前返回状态码${responseCode}无对应Schema配置,请补充校验逻辑`);
    });
}

改造后运行效果

  • 每次测试仅运行当前响应匹配的1条Schema校验,不会出现无关的失败用例
  • 同状态码下的细分错误场景可自动识别匹配,不会错配校验规则
  • 遇到未预先配置的状态码会抛出明确错误,方便后续补全校验覆盖范围

内容的提问来源于stack exchange,提问作者joyousNPC

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 13:24:27