这里是 PostMan 6.0.10.我试图了解如何更好地编写测试脚本,并在阅读了他们的其他 精湛的文档 我仍然对如何查询 &检查从请求返回的 JSON 响应.
具体来说,给定以下 JavaScript 片段:
pm.test("验证响应payload的内容是否正确", function () {//???});
我需要能够查询响应 JSON 并且:
确定响应是单个 JSON 对象还是 JSON 对象数组如果它是一个数组,则确定大小(数组中的元素数)否则,如果它是单个对象,我需要能够查询该对象的特定字段(例如,名为fizzbuzz
"的字段)并获取值和 JSON 类型(字符串、数字, bool, null) 的这些字段例子:
[{嘶嘶":嗡嗡声",富":53},{嘶嘶":博兹",富":291}]
例子:
{嘶嘶":嗡嗡声",富":293}
知道如何对响应负载执行 JSON 检查吗?
解决方案这是基本的,但应该能够获得动态:
pm.test("验证示例一的payload", () => {pm.expect(pm.response.json()[0].fizz).to.equal('buzz')pm.expect(pm.response.json()[0].foo).to.equal(53)pm.expect(pm.response.json()[1].fizz).to.equal('bozz')pm.expect(pm.response.json()[1].foo).to.equal(291)});pm.test("验证示例二的payload", () => {pm.expect(pm.response.json().fizz).to.equal('buzz')pm.expect(pm.response.json().foo).to.equal(293)});
可能值得研究一些基本的 JavaScript 以及如何解析 JSON 对象.p>
PostMan 6.0.10 here. I'm trying to understand how to write test scripts a little better, and after reading their otherwise superb documentation I still have some confusion surrounding how to query & examine the JSON response coming back from requests.
Specifically, given the following snippet of JavaScript:
pm.test("Verify the contents of the response payload are correct", function () {
// ???
});
I need to be able to query the response JSON and:
Determine if the response is a single JSON object or an array of JSON objects If its an array, determine the size (# of elements in the array) Else if its a single object, I need to be able to query that object for specific fields (say, a field called "fizzbuzz
") and obtain the values and JSON types (string, number, bool, null) of those fields
Example:
[
{
"fizz": "buzz",
"foo": 53
},
{
"fizz": "bozz",
"foo": 291
}
]
Example:
{
"fizz": "buzz",
"foo": 293
}
Any ideas how this JSON inspection of the response payloads can be performed?
解决方案This is basic but should work to get the dynamics:
pm.test("Verify payload of example one", () => {
pm.expect(pm.response.json()[0].fizz).to.equal('buzz')
pm.expect(pm.response.json()[0].foo).to.equal(53)
pm.expect(pm.response.json()[1].fizz).to.equal('bozz')
pm.expect(pm.response.json()[1].foo).to.equal(291)
});
pm.test("Verify payload of example two", () => {
pm.expect(pm.response.json().fizz).to.equal('buzz')
pm.expect(pm.response.json().foo).to.equal(293)
});
Might be worth researching some basic JavaScript and how to parse JSON objects.