如何在Postman中校验含多词属性名的响应数组值
解决Postman测试脚本校验数组元素失败问题
问题场景
我在Postman请求中收到如下409冲突响应,想要校验其中Duplicated Subscription数组的首个元素是否包含指定预期文本,但编写的测试脚本第7行执行失败。
响应内容
{ "type": "https://httpstatuses.com/409", "title": "Conflict", "status": 409, "detail": "A resource with the specified parameters already exist", "correlationId": "f976f20f-c9b1-4822-aa15-2b5e5de3555a", "errors": { "Duplicated Subscription": [ "Active subscriptions has reached the limit of 6 for CarrierId=AB, CustomerId=xyz. Cancel existing subscription before subscribing." ] } }
原测试脚本(第7行执行失败)
pm.test("Validate conflict Subscription stauts code", function () { pm.response.to.have.status(409); var jsonData = pm.response.json(); pm.expect(jsonData).to.have.property("title"); pm.expect(jsonData).to.have.property("detail"); pm.expect(jsonData.errors).to.have.property("Duplicated Subscription"); pm.expect(jsonData.errors).to.have.property("Duplicated Subscription")[0].to.contains("Active subscriptions has reached the limit of 6 for CarrierId=AB, CustomerId=xyz. Cancel existing subscription before subscribing."); });
错误原因
第7行的断言写法不符合Chai断言库语法规则:pm.expect(...).to.have.property(...)返回的是Chai断言对象,无法直接用[0]访问数组元素,必须先获取数组本身再做后续断言。
修正后的测试脚本
pm.test("Validate conflict Subscription status code", function () { pm.response.to.have.status(409); var jsonData = pm.response.json(); pm.expect(jsonData).to.have.property("title"); pm.expect(jsonData).to.have.property("detail"); // 确认Duplicated Subscription属性存在且为非空数组 pm.expect(jsonData.errors).to.have.property("Duplicated Subscription"); pm.expect(jsonData.errors["Duplicated Subscription"]).to.be.an("array").that.is.not.empty; // 校验数组首个元素包含指定文本 pm.expect(jsonData.errors["Duplicated Subscription"][0]).to.contains("Active subscriptions has reached the limit of 6 for CarrierId=AB, CustomerId=xyz. Cancel existing subscription before subscribing."); });
说明
- 先通过断言确认
Duplicated Subscription是存在的非空数组,避免因响应结构异常导致后续断言报错 - 直接通过数组下标
[0]获取首个元素后,使用contains断言校验文本内容
内容的提问来源于stack exchange,提问作者ChinS
相关产品推荐
相关产品推荐

