如何使用 Rest Assured 中的断言验证 JSON 响应主体?


我们能够使用 Rest Assured 中的断言验证 JSON 响应主体。这借助 Hamcrest 断言实现。它使用 Matcher 类进行断言。

为了使用 Hamcrest,我们必须在 Maven 项目的 pom.xml 文件中添加 Hamcrest Core 依赖项。可在以下链接获取此依赖项的链接 −

https://mvnrepository.com/artifact/org.hamcrest/hamcrest-core

我们将通过 Postman 向模拟 API 发送 GET 请求,并观察响应。

使用 Rest Assured,我们将验证响应体中 Location 的值。

代码实现

import org.hamcrest.Matchers;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import io.restassured.RestAssured;
public class NewTest {
   @Test
   public void ressponseAssertion() {

      //base URL
      RestAssured.baseURI = "https://run.mocky.io";

      //GET operation
      given() .when().get("/v3/6c6ed634-5e78-4b80-94c7-cf17c04c7055").
      then().log().all()

      //verify status code as 200
      .assertThat().statusCode(200)

      //verify body
      .body("Location", Matchers.equalTo("Makinac Island"))

      //verify header
      .header("Content-Length" , "57");
   }
}

输出

更新时间: 17-Nov-2021

10K+ 浏览

开启你的职业生涯

完成课程即可获得认证

开始学习
广告
© . All rights reserved.