Postman中if-else实现JSON Schema响应校验测试报错求助
我希望在Postman中针对成功和失败两种响应场景分别进行JSON Schema校验测试,编写的测试脚本如下:
positiveSchema = { /* 成功响应的JSON Schema */ } negativeSchema= { /* 失败响应的JSON Schema */ } if (pm.response.to.be.success) { pm.test("Positive response", function () { pm.response.to.have.jsonSchema(positiveSchema); }); } else { pm.test("Negative response", function () { pm.response.to.have.jsonSchema(negativeSchema); }); }
预期逻辑:响应状态码为2XX时校验成功场景的JSON Schema,非2XX时校验失败场景的JSON Schema,但执行时出现错误:
There was an error in evaluating the test script: AssertionError: expected response code to be 2XX but found 500
尝试过改用if (pm.response.to.be.success) else if (pm.response.to.be.error)的判断模式,也试过使用tv4校验:
pm.test('Schema is valid', function () { pm.expect(tv4.validate(pm.response, negativeSchema)).to.be.true; });
但tv4校验无效(Postman版本支持该工具)。若不使用if-else,测试能运行但会出现一个通过一个失败的结果,不符合需求。
1. 脚本判断条件的核心问题
pm.response.to.be.success不是布尔值判断,它本身就是Postman的断言语句。把它放在if条件中时,Postman会直接执行这个断言,一旦响应状态码不是2XX,就会抛出你看到的AssertionError,根本走不到else分支的逻辑。
正确做法是直接判断响应状态码的数值范围,用纯布尔逻辑分支:
const positiveSchema = { /* 成功响应的JSON Schema */ }; const negativeSchema = { /* 失败响应的JSON Schema */ }; // 直接判断状态码是否属于2XX范围 if (pm.response.code >= 200 && pm.response.code < 300) { pm.test("Positive response schema validation", function () { pm.response.to.have.jsonSchema(positiveSchema); }); } else { pm.test("Negative response schema validation", function () { pm.response.to.have.jsonSchema(negativeSchema); }); }
2. tv4校验无效的原因
tv4的validate方法第一个参数需要传入解析后的JSON响应数据,而非整个pm.response对象。你需要先把响应体解析成JSON对象再传入:
pm.test('Negative schema validation with tv4', function () { const responseData = pm.response.json(); pm.expect(tv4.validate(responseData, negativeSchema)).to.be.true; });
如果需要结合分支逻辑,也可以把tv4的写法整合到上述if-else结构中,确保只执行对应场景的校验。
内容的提问来源于stack exchange,提问作者Igor Martakov

