[英]How to validate a JSON 2D Array using Rest Assured?
這是問題。
第 1 部分:
{
"people": [
{
"name": "John",
"address": "765 the the",
"number": "3277772345",
},
{
"name": "Lee",
"address": "456 no where",
"number": "7189875432",
},
]
}
我想驗證數字字段,即數字是否為"7189875432"
。 "7189875432"
的 JSON 路徑是: people[1]. number
people[1]. number
(在 JSON 數組中)。
為此,我做了以下研究:
List<String> value=
given()
.when()
.get("/person")
.then()
.extract()
.path("people.findAll{it.number=='7189875432}. number");
If (value.isEmpty)
assert.fail();
這個測試會通過。 基本上,如果該值存在,它將返回該值的列表。 這個我明白。 但是現在假設我有一個 JSON,例如:
第 2 部分
{
"people": [
{
"name": "John",
"address": "765 the the",
"phoneno": [
{
"number": "3277772345",
},
{
"number": "654787654",
},
]
},
{
"name": "Lee",
"address": "456 no where",
"phoneno": [
{
"number": "7189875432",
},
{
"number": "8976542234",
},
{
"number": "987654321",
},
]
},
]
}
現在我想驗證電話號碼"987654321"
是否在 JSON 中。 JSON 路徑: people[1].phoneno[2].number
List<String> value=
given()
.when()
.get("/person")
.then()
.extract()
.path("people.phoneno.findAll{it.number=='987654321'}. number");
If (value.isEmpty)
assert.fail();
此測試將失敗,因為它將返回一個空字符串。
如果我對路徑進行硬編碼,例如:
.path("people[1].phoneno.findAll{it.number=='987654321'}. number");
If (value.isEmpty)
assert.fail(); // this test will pass
另外,如果我這樣做的話
.path("people.phoneno. number");
I would get a list such as [["987654321", "3277772345", "7189875432", "8976542234"]]
帶有 JSON 中所有數字的列表。
所以我的問題是我們如何驗證在另一個數組中有一個數組的 JSON 路徑? 我不想硬編碼任何東西。
注意:唯一可用的信息是數字,即"987654321"
您始終可以編寫自己的自定義匹配器:
private static Matcher<List<List<String>>> containsItem(String item) {
return new TypeSafeDiagnosingMatcher<List<List<String>>>() {
@Override
protected boolean matchesSafely(List<List<String>> items, Description mismatchDescription) {
return items.stream().flatMap(Collection::stream).collect(toList()).contains(item);
}
@Override
public void describeTo(Description description) {
description.appendText(
String.format("(a two-dimensional collection containing \"%s\")", item));
}
};
}
然后使用這個匹配器:
given()
.when()
.get("/person")
.then()
.body("people.phoneno.number", containsItem("987654321"));
為了使這個匹配器更加可重用,請使輸入類型通用:
private static <T> Matcher<List<List<T>>> containsItem(T item) {...}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.