我必须断言两个具有相同键的json对象,它们包含在json数组中,如下所示。
响应值
[{"message":"Rest Endpoint不应为空"},{"message":"无效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]");
找到解决方案
//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"));
您可以使用hasItem和assertThat
,只需将jsonArray
转换为List
即可。
Assert.assertThat(Arrays.asList(exampleStringArray), hasItem("Rest Endpoint should not be empty"));
Assert.assertThat(Arrays.asList(exampleStringArray), hasItem("Invalid URL"));
其中CCD_ 4是CCD_。
如果您的用例使用Maven,我会包含这个库
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
这将帮助您比较对象,而不必担心顺序。
这里还有一个如何使用它的链接。