Java代码,用于比较JsonPath和Excel输入值的响应。使用JSONPath,我们应该能够验证响应
public void getAirportDetailswithcity(String eLongitude,String eLaititude,String eCity)
{
//1. define the base url
//http://restapi.demoqa.com/utilities/weather/city
RestAssured.baseURI = prop.getProperty("serviceurl1");
//2. define the http request:
RequestSpecification httpRequest = RestAssured.given()
.filter(new ResponseLoggingFilter())
.filter(new RequestLoggingFilter());
JSONObject requestParams = new JSONObject();
requestParams.put("longitude", eLongitude);
requestParams.put("latitude", eLaititude);
requestParams.put("city", eCity);
httpRequest.headers("Content-Type", "application/json");
httpRequest.body(requestParams.toJSONString());
//httpRequest.queryParam("city", "Mumbai");
//3. make a request/execute the request:
Response response = httpRequest.request(Method.GET);
//System.out.println("Response Time : " + response.getTime());
System.out.println("Response Time : " +response.getTimeIn(TimeUnit.SECONDS));
//4. get the response body:
String responseBody = response.getBody().asString();
System.out.println("Response Body is: "+ responseBody);
logger.info("Response Body==>"+responseBody);
//validate city name or validate the key or value
Assert.assertEquals(responseBody.contains(eCity), true);
System.out.println("City is: "+ eCity);
//5. get the status code and validate it:
int statusCode = response.getStatusCode();
System.out.println("the status code is: "+ statusCode);
Assert.assertEquals(statusCode, TestUtil.RESPONSE_CODE_200);
System.out.println("the status line is: "+ response.getStatusLine());
//6. get the headers:
Headers headers = response.getHeaders();
System.out.println(headers);
String contentType = response.getHeader("Content-Type");
System.out.println("the value of content-type header is: "+ contentType);
String contentLength = response.getHeader("Content-Length");
System.out.println("the value of Content-Length header is: "+ contentLength);
//String restime = response.getTimeIn("Seconds");
//get the key value by using JsonPath:
//Comment
JsonPath jsonPathValue = response.jsonPath();
//jsonPathValue.prettyPrint();
String longitudeVal = jsonPathValue.get("longitude");
//String longitudeVal = jsonPathValue.getString("data.longitude");
System.out.println("the value of Longitude is: "+ longitudeVal);
Assert.assertEquals(longitudeVal,eLongitude);
Assert.assertEquals(responseBody.contains("longitude"), true);
System.out.println("Longitude is: "+ eLongitude);
Assert.assertEquals(responseBody.contains("latitude"), true);
System.out.println("Laititude is: "+ eLaititude);
}
Postman中的JSON响应如下所示 { “响应”:{ “代码”:200, “ status”:“成功”, “警告”:[ { “ message”:“成功”, “ type”:“成功”, “可跳过”:1 } ], “ from_cache”:0, “ is_data”:1 }, “数据”:[ { “ id”:6004, “ airport_name”:“亚当浦机场”, “ city”:“ Adampur”, “ country”:“印度”, “ iata”:“ AIP”, “ icao”:“ VIAX”, “纬度”:“ 31.4338”, “经度”:“ 75.758797”, “海拔”:“ 775” } ] }