首页 > 解决方案 > RestAssured - 在调用 API B 的主体中使用来自 API A 的响应值

问题描述

所以我有一个需要调用的 API (API A) 来提供值。我在下一个测试中需要这些值(API B)

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", productCategoriesMap);
    System.out.println(jsonRequest);

    Object RothHysa = RestAssured
        .given()
                .header("one-data-correlation-id", CommonUtility.getGuid())
                .body(jsonRequest)
            .when()
                .post(functionUrl)
            .then()
                .extract().response()
            .then().assertThat()
                .statusCode(200)
            .and()
                .assertThat().body("idofproduct", equalTo(Arrays.asList("xxxxxxx-xxxx-xxx-xxxxxx-xxxxxx")))
            .log().all()
                .extract()
                .jsonPath()
                .get("idofproduct");

    context.setAttribute("idofproduct", idToBeUsed);

    System.out.println(idToBeUsed);
}

我断言的值是一个数组 - API 将其返回为 ['value'] ,这会在下一次测试中引起问题,因为它需要作为字符串传递。我试过以各种方式将其转换为字符串,但它们没有奏效。API B 测试:

public void Step1PCN(ITestContext context) {

String identifierIRArothHYSA1 = (String) context.getAttribute("identifier");

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)
        .extract().response()
    .then().assertThat()
        .statusCode(200)
    .and()
        .assertThat().body("status.StatusMessage", equalTo("Success"))
    .log().all()
        .extract()
        .jsonPath()
        .get("idForTestB");


context.setAttribute("idForTestB", idForTestB);

}

然而 idToBeUsed 的值总是 [xxx-xxx-xxxxxx] 但在这个测试中它需要是一个字符串。

标签: javarest-assured

解决方案


您可以将 var 保存RothHysaList<String>而不是Object.

List<String> RothHysa = RestAssured.given()...get("idofproduct");
context.setAttribute("idForTestB", RothHysa.get(0));

推荐阅读