我必须断言两个具有相同键的json对象,它们包含在JSON数组中,如下所示。
响应值
{“消息”:“Rest端点不应为空”},{“消息”:“无效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]");
发布于 2019-11-18 10:48:30
您可以使用hasItem和assertThat
,只需将jsonArray
转换为List
即可。
Assert.assertThat(Arrays.asList(exampleStringArray), hasItem("Rest Endpoint should not be empty"));
Assert.assertThat(Arrays.asList(exampleStringArray), hasItem("Invalid URL"));
其中hasItem
是org.hamcrest.core
的一部分。
发布于 2019-11-18 21:54:59
找到了解决方案
//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"));
发布于 2019-11-18 10:44:36
如果您在用例中使用Maven,我将包括这个库
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
这将有助于您在不需要担心顺序的情况下进行对象比较。
下面是一个关于如何使用它的链接。
https://stackoverflow.com/questions/58920815
复制相似问题