如何在 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"));
   }
}

輸出

更新於:2021 年 11 月 22 日

9K+ 瀏覽

開啟你的職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.