如何在 Rest Assured 中从嵌套列表中获取值?
rest assureddynamic programmingprogramming
我们可以在 Rest Assured 中从嵌套列表中获取值。这是在 extract 方法的帮助下完成的。要获取项目,我们必须使用 path 方法(在 extract 方法之后)并在我们想要获取的响应中传递该项目。
我们首先通过 Postman 在模拟 API URL 上发送 GET 请求,并查看其带有嵌套列表的响应。
示例
代码实现
import org.testng.annotations.Test; import static io.restassured.RestAssured.given; import java.util.ArrayList; import io.restassured.RestAssured; import io.restassured.http.ContentType; public class NewTest { @Test public void getRequest() { //基本 URL RestAssured.baseURI = "https://run.mocky.io/v3"; RestAssured.basePath = "/23ab8486-7d8d-41e4-be27-d603c767d745"; //GET 请求的响应 given() .when().get().prettyPrint(); //从 Response 中提取值 String name = given().contentType(ContentType.JSON).get() .then().extract().path("name"); System.out.println(name); String age = given().contentType(ContentType.JSON).get() .then().extract().path("age"); System.out.println(age); //从 Response 中的嵌套列表中提取值 ArrayList<String> s = given().contentType(ContentType.JSON).get() .then().extract().path("subjects"); for(String subject: s) { System.out.println(subject); } } }