api - 如何从 Json 响应中提取特定值并在 Rest Assured Automation Testing 的输入负载 json 文件中使用该值
问题描述
我没有使用任何 POJO 类。相反,我使用外部 json 文件作为我的 2 个 API(获取 API 和删除 API)的有效负载文件。
添加 API >> 添加书名、书架、其他书籍详细信息以及唯一的 place_id。删除 API >> 用于使用上面唯一的 place_id 从特定机架中删除一本书。
由于我使用的是外部 json 有效负载输入文件,请告诉我如何传递从 GET API 获取的“place_id”并将此 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-simple 库来执行此操作。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;
您必须达到以下要求;
从 Add Place API json 响应中检索 place_id
从 json 文件中读取 Delete Place API 的请求正文
替换 Delete Place API 请求正文中的 place_id 值
将新的请求正文写入 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(); }
推荐阅读
- r - 如何链接 ifelse?
- javascript - 我正在制作的网站导航栏的小 CSS 错误
- flutter - 我们如何编写一个自定义地图,其中每个街区(房子)都可以在颤动中点击?
- node.js - 如何解决 npm 错误“npm ERR!errno -4058”“nom ERR!enoent”
- kotlin - 如何在 Kotlin 中创建具有特定类型参数的“类”实例?
- flutter - Flutter - 无法将类字段传递给子组件
- go - golang os.FileMode对应drwxrwxr-x?
- linux - 如果 AWS Sessions Manager 在 EC2 中执行文件,执行的 EC2 中的哪个用户执行该文件?
- c# - xUnit:在失败的情况下如何运行附加代码
- apache-spark - Spark,左连接上的OOM(内部很好),如何禁用特定数据帧的广播?