PostMan测试脚本:检查响应JSON的内容 [英] PostMan Test scripts: Inspecting contents of response JSON
问题描述
PostMan 6.0.10在这里。我试图理解如何更好地编写测试脚本,并在阅读它们后以其他方式精湛的文档我仍然对如何查询&检查来自请求的JSON响应。
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.
具体来说,考虑以下JavaScript代码段:
Specifically, given the following snippet of JavaScript:
pm.test("Verify the contents of the response payload are correct", function () {
// ???
});
我需要能够查询响应JSON和:
I need to be able to query the response JSON and:
- 确定响应是单个JSON对象还是JSON对象数组
- 如果响应是数组,请确定大小(
- 否则,如果它是单个对象,则我需要能够查询该对象的特定字段(例如,名为
fizzbuzz
)并获取这些字段的值和JSON类型(字符串,数字,布尔值,空值)
- 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
示例:
[
{
"fizz": "buzz",
"foo": 53
},
{
"fizz": "bozz",
"foo": 291
}
]
场景# 2:JSON响应是单个对象
示例:
Scenario #2: JSON response is a single object
Example:
{
"fizz": "buzz",
"foo": 293
}
有什么想法可以对响应负载进行JSON检查吗?
推荐答案
这是基本的,但应该可以获取动态信息。
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)
});
可能值得研究一些基本的JavaScript以及如何解析 JSON对象。
Might be worth researching some basic JavaScript and how to parse JSON objects.
这篇关于PostMan测试脚本:检查响应JSON的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!