在Postman中使用BDD语法访问JSON响应字段的方法咨询
嗨,这个问题我之前也碰到过!核心原因是Postman返回的response.body默认是JSON格式的字符串,不是可直接访问的JavaScript对象,所以你直接用点语法response.body.Id1肯定拿不到值~
解决步骤很简单,先把响应体解析成JS对象,再结合postman-bdd的BDD语法写测试就行,给你两种常用的写法:
1. 先解析再用describe/it断言
// 第一步:把响应体转成可操作的JSON对象 const resData = pm.response.json(); // 第二步:用postman-bdd的BDD风格写测试 describe('GET请求响应字段验证', () => { it('Id1的各项数值应该符合预期', () => { expect(resData.Id1.a).to.equal(84); expect(resData.Id1.b).to.equal(74); expect(resData.Id1.c).to.equal(7); expect(resData.Id1.d).to.equal(3); expect(resData.Id1.e).to.equal(91); }); it('Id2的各项数值应该符合预期', () => { expect(resData.Id2.a).to.equal(25); expect(resData.Id2.b).to.equal(51); expect(resData.Id2.c).to.equal(93); expect(resData.Id2.d).to.equal(97); expect(resData.Id2.e).to.equal(1); }); });
2. 用postman-bdd的链式given/when/then语法
如果习惯更贴合BDD场景的链式写法,可以把解析后的对象存在变量里,再在断言中调用:
given('我已解析响应体', () => { pm.variables.set('parsedRes', pm.response.json()); }) .when('验证Id1字段', () => {}) .then('Id1.a应该等于84', () => { expect(pm.variables.get('parsedRes').Id1.a).to.equal(84); }) .then('Id1.b应该等于74', () => { expect(pm.variables.get('parsedRes').Id1.b).to.equal(74); });
另外,你之前用console.log调试的话,也需要先解析:
// 这样就能正确打印Id1的内容了 console.log(JSON.parse(response.body).Id1); // 或者用Postman自带的快捷方法 console.log(pm.response.json().Id1);
内容的提问来源于stack exchange,提问作者QA Prof
相关产品推荐
相关产品推荐

