如何在 JSON 数组中断言两个具有相同键但值不同的 JSON 对象

How to assert two JSON objects which have the same keys but different in values inside of a JSON array

我必须断言两个 json 具有相同键的对象,它们包含在 JSON 数组中,如下所示。

响应值

[{"message":"Rest Endpoint should not be empty"},{"message":"Invalid URL"}]

但是当我断言响应时,我遇到了一个问题,对象没有按照我尝试断言的方式接收,因为响应对象的顺序有时会发生变化,这会导致断言失败。

下面是我目前用来断言对象的代码。

Assert.assertEquals(jsonArray.getJSONObject(0).get("message").toString(), "Rest Endpoint should not be empty");

Assert.assertEquals(jsonArray.getJSONObject(1).get("message").toString(), "Invalid URL");

有时我收到的信息会导致断言错误。

jsonArray.getJSONObject(0).get("message").toString() as "Invalid URL" and 
jsonArray.getJSONObject(1).get("message").toString() as "Rest Endpoint should not be empty"

完整代码块

//Requesting the resource API (save) with Payload
Response response = RestAssured.given().contentType("application/json").body(mydata).post("/api/v1/applications");
logger.info("/Save - Request sent to the API");

//Check valid Json responce
JSONArray jsonArray = new JSONArray(response.body().asString());
System.out.println(jsonArray.length());
Assert.assertEquals(jsonArray.length(), 2);
logger.info("/Save - Json Response validity pass");

//Check Response status code
Assert.assertEquals(response.getStatusCode(), 400);
logger.info("/Save - Responce code 400 OK");

//Check Response Objects received       
Assert.assertEquals(jsonArray.getJSONObject(0).get("message").toString(), "Rest Endpoint should not be empty");          
Assert.assertEquals(jsonArray.getJSONObject(1).get("message").toString(), "Invalid URL");
logger.info("/getAllApplications - Json Response received as :" + jsonArray.getJSONObject(0).get("message").toString());
logger.info("/getAllApplications - Json Response received as :" + jsonArray.getJSONObject(1).get("message").toString());
logger.info("/Save -3 API Testing Completed [Test 'RestEndPoint' field validation]");

如果您将 Maven 用于您的用例,我会包含这个库

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.8</version>
</dependency>

这应该可以帮助您比较对象而不必担心顺序。

这里还有 link 如何使用它。

您可以使用 hasItem 和 assertThat,只需将 jsonArray 转换为 List

Assert.assertThat(Arrays.asList(exampleStringArray), hasItem("Rest Endpoint should not be empty"));
Assert.assertThat(Arrays.asList(exampleStringArray), hasItem("Invalid URL"));

其中 hasItemorg.hamcrest.core 的一部分。

找到解决方案

//Create a string list and iterate the Json array to fetch the required text with the same key 

List<String> responseList = new ArrayList<String>(jsonArray.length());

for (int i = 0; i < jsonArray.length(); i++) {
                            responseList.add((jsonArray.getJSONObject(i).getString("message")));

}

//Assert the list
org.junit.Assert.assertThat(responseList, hasItems("Rest Endpoint should not be empty", "Invalid URL"));