java - 通过 RestAssured 在 JSON 中进行多个匹配断言

标签 java rest-assured matcher hamcrest rest-assured-jsonpath

我有几个 JSON 对象作为响应,其中每个对象都包含特定的 id。

{
"data": [{
        "id": 1,
        "status": {
            "id": 0
        }
    },
    {
        "id": 2,
        "status": {
            "id": 0
        }
    },
    {
        "id": 3,
        "status": {
            "id": 0
        }

    }
]

}

我需要测试每个 data.status.id 是否具有特定值:

    then().
        spec(basicResponse).
        body("data.status.id", equalTo(0));

但是 equalTo 匹配器立即将期望值与找到的 id 的整个列表进行比较。不是每个人单独找到id。

java.lang.AssertionError: 1 expectation failed.
JSON path data.status.id doesn't match.
Expected: 0
  Actual: [0, 0, 0]

如何在不将响应数据提取到 List 的情况下测试它,然后通过 foreach 或类似的东西检查它?

int statusNeeded = 0;
            List<int> idsList = given().
                     get(Endpoints.GetCampaigns).
                 then().
                     extract().body().jsonPath().getList("data.status.id");

    for (int statusId: idsList)
    if(!statusNeeded.equals(statusId)) Assert.fail("Some id is not " + statusNeeded);

最佳答案

您可以按照以下方法进行操作

String res = given().when().get("http://localhost:3000/posts/CtQy1bt").then().log().all().extract().response().asString();

JsonPath js = new JsonPath(res);

int Count = js.get("data.size()");

for (int i=0;i<Count;i++) {
    int value = js.get("data["+i+"].status.id");
    Assert.assertEquals(value, 0);
}

我在这里使用了 JsonPath,并使用 for 循环来迭代 data[].status.id 数组。

根据您的要求将其断言为 0 的预期值

如果 status.id 的值不为 0,则断言将失败 - 示例如下

{
    "data": [
        {
            "id": 1,
            "status": {
                "id": 0
            }
        },
        {
            "id": 2,
            "status": {
                "id": 5
            }
        },
        {
            "id": 3,
            "status": {
                "id": 0
            }
        }
    ],
    "id": "nmBlS8t"
}
Exception in thread "main" java.lang.AssertionError: expected [0] but found [5]
    at org.testng.Assert.fail(Assert.java:97)
    at org.testng.Assert.assertEqualsImpl(Assert.java:136)
    at org.testng.Assert.assertEquals(Assert.java:118)
    at org.testng.Assert.assertEquals(Assert.java:839)
    at org.testng.Assert.assertEquals(Assert.java:849)
    at Stack5.main(Stack5.java:25)

关于java - 通过 RestAssured 在 JSON 中进行多个匹配断言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61317232/

相关文章:

java - Android:目录和子目录列出连续 Activity 问题

java - Java中getText()方法返回的值

java - 如何像 postman 提供的保存和下载方式一样放心地保存和下载文件

java - 使用 restAssured 测试 Spring Boot Rest 应用程序

java - 如何使用 find() 而不改变 Matcher 的状态?

java - 将图像与实体一起保存在数据库中

java - java 统计字符串出现次数

java - Maven 项目在 eclipse 中工作,但不能在命令行中工作

java - 我希望 Java Pattern.compile 识别正整数或负整数或小数

android - UriMatcher 是否能够匹配自定义 http 链接?