如何在 Rest Assured 中驗證請求的響應時間?


我們可以驗證 Rest Assured 中請求的響應時間。請求傳送到伺服器後到接收到響應之間經過的時間稱為響應時間。

預設情況下,響應時間以毫秒為單位獲取。要使用 Matchers 驗證響應時間,我們需要使用 ValidatableResponseOptions 的以下過載方法:

  • **time(matcher)** - 它使用作為引數傳遞給方法的匹配器來驗證以毫秒為單位的響應時間。
  • **time(matcher, time unit)** - 它使用匹配器和時間單位作為引數來驗證響應時間。

我們將藉助 Hamcrest 框架進行斷言,該框架使用 Matcher 類進行斷言。要使用 Hamcrest,我們必須在 Maven 專案的 pom.xml 中新增 Hamcrest Core 依賴項。此依賴項的連結如下:

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

示例

程式碼實現

import org.hamcrest.Matchers;
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
public class NewTest {
   @Test
   public void verifyResTime() {

      //base URI with Rest Assured class
      RestAssured.baseURI ="https://tutorialspoint.tw/index.htm";

      //input details
      RequestSpecification r = RestAssured.given();

      // GET request
      Response res = r.get();

      //obtain Response as string
      String j = res.asString();

      // obtain ValidatableResponse type
      ValidatableResponse v = res.then();

      //verify response time lesser than 1000 milliseconds
      v.time(Matchers.lessThan(1000L));
   }
}

輸出

更新於:2021年11月18日

3K+ 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.