如何从Json响应中提取特定值,并在Rest Assured Automation Testing中的输入有效负载Jso



我没有使用任何POJO类。相反,我使用Externaljson文件作为我的API的2个(Get API和Delete API(的有效负载文件。

添加API>gt;添加图书名称、书架、其他图书详细信息以及唯一的place_id。删除API>gt;用于使用上面的唯一place_id从特定书架上删除书籍。

由于我使用的是外部json负载输入文件,请让我知道传递"place_id";从GET API获取并将此place_id发送到DELETE API外部json文件,然后使用它

在下面添加Place API:此API在响应中返回唯一的Place_ID

{
"location": {
"lat": -38.383494,
"lng": 33.427362
},
"accuracy": 50,
"name": "Frontline house 1",
"phone_number": "(+91) 983 893 3937",
"address": "2951, side layout, cohen 09",
"types": [
"shoe park",
"shop"
],
"website": "http://google.com",
"language": "French-IN"
}

删除下方的API

{
"place_id": "<need to insert place_id from above response>"
}

您可以使用java中的json简单库来实现这一点。json简单maven存储库

进口

import io.restassured.RestAssured;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import org.json.simple.JSONObject
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

你必须做到以下几点;

  1. 从Add place API json响应检索place_id

  2. 从json文件中读取Delete Place API的请求主体

  3. 替换Delete place API 请求主体中的place_id值

  4. 将新的请求主体写入Delete Place API json文件

    // Retrieve place_id from Add Place API json response
    Response response = RestAssured
    .when()
    .get("add_place_api_url")
    .then()
    .extract()
    .response();
    JsonPath jsonPath = response.jsonPath();
    String placeId = jsonPath.get("place_id");
    // Read request body of Delete Place API from json file
    JSONObject jsonObject = new JSONObject();
    JSONParser parser = new JSONParser();
    try {
    Object obj = parser.parse(new FileReader("path/DeletePlaceRequestBody.json"));
    jsonObject = (JSONObject) obj;
    // Replace the place_id value in request body of Delete Place API
    jsonObject.replace("place_id", placeId);
    } catch (IOException e) {
    e.printStackTrace();
    } catch (ParseException e) {
    e.printStackTrace();
    }
    // Write the new request body to Delete Place API json file
    try {
    FileWriter file = new FileWriter("DeletePlaceRequestBody.json");
    file.write(jsonObject.toString());
    file.flush();
    file.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    

最新更新