如何在 Rest Assured 的响应中使用断言?

rest assureddynamic programmingprogramming

我们可以在 Rest Assured 的响应中使用断言。要获取响应,我们需要使用 Response.body 或 Response.getBody 方法。这两个方法都是 Response 接口的一部分。

获取响应后,会使用 asString 方法将其转换为字符串。此方法是 ResponseBody 接口的一部分。然后,我们可以借助 jsonPath 方法获取响应主体的 JSON 表示形式。最后,我们将验证 JSON 内容,以探索特定的 JSON 键及其值。

我们首先通过 Postman 向模拟 API URL 发送 GET 请求,并查看响应主体。

使用 Rest Assured,我们将检查键 Location 的值是否为 Michigan。

示例

代码实现

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() {

      // 包含 Rest Assured 类的基本 URI
      RestAssured.baseURI = "https://run.mocky.io/v3";

      // 输入详细信息
      RequestSpecification h = RestAssured.given();

      // 获取响应
      Response r = h.get("/0cb0e329-3dc8-4976-a14b-5e5e80e3db92");

      // 响应正文
      ResponseBody bdy = r.getBody();

      //将响应体转换为字符串
      String b = bdy.asString();

      //将响应体转换为 JSON 格式
      JsonPath j = r.jsonPath();

      //获取 Location 键的值
      String l = j.get("Location");
      System.out.println(l);

      // 验证键的值
      Assert.assertTrue(l.equalsIgnoreCase("Michigan"));
   }
}

输出


相关文章