繁体   English   中英

如何使用 Rest Assured 验证 JSON 2D 数组?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM