如何在 Rest Assured 中在响应中使用 Assertion?
我们可以在 Rest Assured 中的响应中使用 Assertion。要获取响应,我们需要使用 - Response.body 或 Response.getBody 方法。这两种方法都是响应接口的一部分。
一旦获得响应,它将通过 asString 方法转换为字符串。该方法是 ResponseBody 接口的一部分。然后,我们可以借助 jsonPath 方法获得响应体的 JSON 表示形式。最后,我们将验证 JSON 内容以使用其值来探索特定的 JSON 键。
我们首先将通过 Postman 对模拟 API URL 发送 GET 请求,然后查看响应正文。

使用 Rest Assured,我们将检查键值 - Location 是否为密歇根州。
示例
代码实现
import org.testng.Assert;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.*;
import io.restassured.RestAssured;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import io.restassured.response.ResponseBody;
import io.restassured.specification.RequestSpecification;
public class NewTest {
@Test
void respAssertion() {
//base URI with Rest Assured class
RestAssured.baseURI = "https://run.mocky.io/v3";
//input details
RequestSpecification h = RestAssured.given();
//get response
Response r = h.get("/0cb0e329-3dc8-4976-a14b-5e5e80e3db92");
//Response body
ResponseBody bdy = r.getBody();
//convert response body to string
String b = bdy.asString();
//JSON Representation from Response Body
JsonPath j = r.jsonPath();
//Get value of Location Key
String l = j.get("Location");
System.out.println(l);
// verify the value of key
Assert.assertTrue(l.equalsIgnoreCase("Michigan"));
}
}输出

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP