RestAssured如何将API A返回的数组值转为字符串传入API B请求体
RestAssured数组类型返回值提取转字符串解决方案
问题根源
- 调用API A时用
jsonPath.get("idofproduct")提取返回值,因idofproduct是数组结构,默认提取结果为List类型而非字符串 - 原有代码存在两处变量对应错误:API A中提取结果赋值给了
RothHysa变量,但存入上下文用的是未定义的idToBeUsed;API B中从上下文取值的keyidentifier和API A存入的idofproduct不匹配
解决方案
第一步:修改API A的提取逻辑
直接通过JsonPath索引取数组第一个元素,拿到字符串类型的id,修正后的代码如下:
public class testA { String functionUrl = "https://dev.testA.v2"; @Test public void RothHysa(ITestContext context) { Map<String, Object> jsonRequest = new HashMap<String, Object>(); jsonRequest.put("product", "thisistheproduct"); Map<String,String> jurisdictionMap = new HashMap<>(); jurisdictionMap.put("category", "COUNTRY"); jurisdictionMap.put("name", "US"); jsonRequest.put("productCategories", jurisdictionMap); System.out.println(jsonRequest); // 直接用getString提取数组第一个元素,得到字符串类型id String idToBeUsed = RestAssured .given() .header("one-data-correlation-id", CommonUtility.getGuid()) .body(jsonRequest) .when() .post(functionUrl) .then() .assertThat() .statusCode(200) .and() .body("idofproduct", equalTo(Arrays.asList("xxxxxxx-xxxx-xxx-xxxxxx-xxxxxx"))) .log().all() .extract() .jsonPath() // 加[0]取数组第一个元素 .getString("idofproduct[0]"); context.setAttribute("idofproduct", idToBeUsed); System.out.println(idToBeUsed); } }
第二步:修改API B的取值逻辑
从上下文取对应key的字符串值直接使用即可:
public void Step1PCN(ITestContext context) { // 取API A存入的idofproduct,就是字符串类型 String idToBeUsed = (String) context.getAttribute("idofproduct"); Map<String,Object> jsonRequest = new HashMap<>(); Map<String,String> value = new HashMap<>(); value.put("key","value"); value.put("key","value"); jsonRequest.put("key", value); Map<String,String> value1 = new HashMap<>(); value1.put("key","value"); value1.put("key","value"); value1.put("key","value"); jsonRequest.put("key", value1); jsonRequest.put("key", "value"); jsonRequest.put("productID", idToBeUsed); Object idForTestB = RestAssured .given() .header("one-data-correlation-id", CommonUtility.getGuid()) .body(jsonRequest) .when() .post(functionUrl) .then() .contentType(ContentType.JSON) .assertThat() .statusCode(200) .and() .body("status.StatusMessage", equalTo("Success")) .log().all() .extract() .jsonPath() .get("idForTestB"); context.setAttribute("idForTestB", idForTestB); }
可选优化(避免空指针)
如果数组可能为空,可先提取为List再判断取值:
List<String> idList = RestAssured.xxx.extract().jsonPath().getList("idofproduct", String.class); if (!idList.isEmpty()) { String idToBeUsed = idList.get(0); context.setAttribute("idofproduct", idToBeUsed); } else { // 抛出异常或标记用例失败 }
内容的提问来源于stack exchange,提问作者CatAndPlantGuy
相关产品推荐
相关产品推荐

