我遇到了一个问题,我希望验证 JSON 数组的内容。以下是回应:
[
{
"airportId": "5d5448a4-f7d7-461d-8ec0-7881719cc013",
"code": "HNL",
"name": "Honolulu, Oahu",
"location": {
"longitude": -157.925,
"latitude": 21.321667
},
"cityId": "7b244a1b-b2fb-4e9b-a611-3f3107f9adfc",
"city": "Honolulu",
"countryCode": "US",
"themes": [
"BEACH",
"HISTORIC",
"OUTDOORS",
"ROMANTIC",
"SHOPPING"
],
"pointsOfSale": [
"US"
]
},
{
"airportId": "896d2041-5083-4d5d-b11b-575d388e8e6f",
"code": "NRI",
"name": "Shangri-la Airport",
"location": {
"longitude": -157.794932,
"latitude": 21.256836
},
"cityId": "7b244a1b-b2fb-4e9b-a611-3f3107f9adfc",
"city": "Honolulu",
"countryCode": "US",
"themes": [],
"pointsOfSale": [
"US"
]
},
{
"airportId": "0bf1e80e-bf08-4a62-9f18-41328cc62fc4",
"code": "HIK",
"name": "Hickam AFB Airport",
"location": {
"longitude": -157.8583333,
"latitude": 21.3069444
},
"cityId": "7b244a1b-b2fb-4e9b-a611-3f3107f9adfc",
"city": "Honolulu",
"countryCode": "US",
"themes": [],
"pointsOfSale": [
"US"
]
},
{
"airportId": "aed7c2eb-54ce-47c2-966f-9e2079506b9c",
"code": "JRF",
"name": "Kalaeloa (John Rodgers Field) Airport",
"location": {
"longitude": -158.0568965,
"latitude": 21.3353909
},
"cityId": "438dd674-e443-466c-a62e-ce6a9c80cf86",
"city": "Kapolei",
"countryCode": "US",
"themes": [],
"pointsOfSale": [
"US"
]
}
]
我想验证檀香山,欧胡岛是否作为响应的一部分存在于名称节点中。我能够使用 JsonPath 类执行此操作,并将所有名称结果存储在列表中。 但是,我希望通过身体和匹配器来做到这一点。
以下是命中端点的代码:
public void getAirport() {
RestAssured.baseURI="https://hotels4.p.rapidapi.com";
Response res = given()
.headers("X-RapidAPI-Host", "cometari-airportsfinder-v1.p.rapidapi.com",
"X-RapidAPI-Key", "KEY_GOES_HERE").
queryParams("radius", "20","lng","-157.895277","lat","21.265600").
when()
.get("/api/airports/by-radius").
then()
.assertThat().statusCode(200)
.and().header("Server", "RapidAPI-1.0.39")
.and().body("name",Matchers.hasItems("Honolulu"))
.and().time(Matchers.lessThan(10000l))
.extract().response();
}
方法1:匹配器.hasItems
.body("name",Matchers.hasItems("Honolulu"))
错误信息:
JSON path name doesn't match.
Expected: (a collection containing "Honolulu")
Actual: [Honolulu, Oahu, Shangri-la Airport, Hickam AFB Airport, Kalaeloa (John Rodgers Field) Airport]
方法2:匹配器。
.body("name",Matchers.contains("Honolulu"))
错误信息:
JSON path name doesn't match.
Expected: iterable containing ["Honolulu"]
Actual: [Honolulu, Oahu, Shangri-la Airport, Hickam AFB Airport, Kalaeloa (John Rodgers Field) Airport]
方法3:匹配器.hasKey
.body("name",Matchers.hasKey("Honolulu"))
错误信息:
JSON path name doesn't match.
Expected: map containing ["Honolulu"->ANYTHING]
Actual: [Honolulu, Oahu, Shangri-la Airport, Hickam AFB Airport, Kalaeloa (John Rodgers Field) Airport]
当我用name[0]
替换name
时,上述方法工作正常,但我不想使用索引执行验证。
名称集合包含"檀香山,瓦胡岛"作为单个值。
Matchers.hasItems("檀香山,瓦胡岛"((应该可以工作