通过 Postman 中的测试断言 JSON 响应中的值

Asserting the values in JSON response through tests in Postman

我的 JSON 响应正文如下:

[
  {
    "_time": "1499996827804",
    "properties": {
      "length": "80",
      "width": "4500"
    }
  }
]

我正在使用 Postman 编写测试以断言长度和宽度的值以及 _time

我写道:

var data = JSON.parse(responseBody);

tests["Check length value"] = data.length === "80";

但是它失败了。有人可以帮忙吗?

您的数据返回到数组中,因此您需要获取数组的第一项。 length 也是 "properties" 对象的子 属性。试试这个:

tests["Check length value"] = data[0].properties.length === "80";

如果您的 JSON 看起来像这样:

[ { "_time": "1499996827804", "properties": { "length": "80", "width": "4500" } } ]

然后您需要修复测试的 data.length === "80" 部分。

首先,您的 JSON 是一个数组,因此您需要选择 data[0] 以获得响应中的第一项(即 { "_time": "1499996827804", "properties": { "length": "80", "width": "4500" } })。然后,看起来您正在尝试检查响应的 length 部分,它位于 properties 对象下。所以你的选择器现在应该是这样的:data[0].properties.

最后,要访问 length 部分,请将 .length 添加到选择器的末尾:data[0].properties.length.

把它们放在一起,你应该有:

tests["Check length value"] = data[0].properties.length === "80";

希望对您有所帮助!