restassured中两个不同json文件之间的依赖关系



我已经使用restAssured创建了两个java类TestA.javaTestB.javaestA.json中读取json,并向端点uri发布请求。TestA.java返回一个带有标签">customerID"的json响应,该标签将为TestB.json的一个标签输入,当我使用"TestB.java"发布请求时,必须从TestB.json中选择customerID。我的代码看起来怎么样?有什么想法吗?

我的代码:

TestA.java
String requestBody = generateString("CreateCustomer.json");
RestAssured.baseURI = "https://localhost:8080";
Response res = given().contentType(ContentType.JSON)
.header("Content-Type", "application/json").header("checkXML", "N").body(requestBody).when()
.post("/restservices/customerHierarchy/customers").then().assertThat()
.statusCode(201).and().body("transactionDetails.statusMessage", equalTo("Success")).and().log().all()
.extract().response();
//converts response to string
String respose = res.asString();
JsonPath jsonRes = new JsonPath(respose);
CustomerID = jsonRes.getString("customerNodeDetails.customerId");
TestA.java response
{
"customerNodeDetails": {
"customerId": "81263"
},

现在我想把这个customerID作为输入传递给testB.jsontestB.java,这是动态的。

TestB.json
"hierarchyNodeDetails": { 
"**customerId**":"", 
"accountNumber": "", 
"startDate": "", 
}

除了后uri 之外,TestA.javaTestB.java看起来几乎相同

提前感谢

这取决于如何分配类:

  1. 如果您想在一个类中编写A和B的测试。声明一个类型为Response/String的本地变量,然后将客户ID存储在该变量中。变量的作用域将存在于所有TestNG方法中。您可以从本地变量设置B.json的客户ID。

    public class Test{  
    String _cust_id; 
    @Test
    public void test_A(){
    // ceremony for getting customer id
    _cust_id = jsonRes.getString("customerNodeDetails.customerId");
    }
    @Test
    public void test_B(){
    // write value of customer id using the variable _cust_id
    }}
    

您可以尝试这种方法,但建议将数据部分分离到dataProvider类中。

  • 如果您想为A和B有单独的类,请使用ITestContext将值从一个类传递到另一个类。

    public class A{
    @Test
    public void test1(ITestContext context){
    context.setAttribute("key", "value");
    }
    }
    public class B{
    @Test
    public void test2(ITestContext context){
    String _attribute = context.getAttribute(key);
    }
    }
    
  • 优雅的方法可以是,使用dataProvider进行类B测试,在那里执行从类a测试中获取customerID的仪式。

    public class DataB{
    @DataProvider
    public static Object[][] _test_data_for_b(){
    // get the customerID
    // create the json for class B
    // return the json required for class B test
    // All these could be achieved as everything has a common scope
    }}
    public class B{
    @Test(dataProvider = "_test_data_for_b", dataProviderClass = DataB.class)
    public void test_B(String _obj){
    // perform the testing
    }}
    

最新更新