首页 > 解决方案 > 我想验证特定字段是否存在并使用 RESTAssured API 自动化测试在控制台上打印

问题描述

我想使用 IntelliJ IDea 中的 RESTAssured API 自动化测试来验证特定字段是否存在并在控制台上打印。该字段在数组中并且有多个值。

我只需要验证字段annualBasePay

[
  {
    "worker": {
      "wID": "137cf520",
      "employeeID": "T19"
    },
    "workerDescription": "Tim Moore",
    "workerId": "T19",
    "userId": "T19",
    "workerType": "Employee",
    "jobRelatedInfoType": {
      "positionTitle": "Systems Architect 5",
      "manager": {
        "wID": "1b1696eabe",
        "employeeID": "T823"
      },
      "adjustedServiceDate": "1976-01-16",
      "annualBasePay": "124917",
      "annualBaseCurrency": null
    }
  }
]

标签: intellij-ideagetrest-assuredrest-assured-jsonpath

解决方案


您可以选择以下两种方式之一:

given()
  ...
  .then()
  .body("jobRelatedInfoType.annualBasePay", hasItems("124917"));

或者

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItems;

Response res = given()...;
List<String> basePays = JsonPath.with(res.asString()).get("jobRelatedInfoType.annualBasePay");
assertThat(basePays, hasItems("124917"));

推荐阅读