如何在 Rest Assured 中验证请求的响应时间?

rest assureddynamic programmingprogramming

我们可以在 Rest Assured 中验证请求的响应时间。请求发送到服务器到收到响应的时间称为响应时间。

响应时间默认以毫秒为单位。要使用 Matcher 验证响应时间,我们需要使用 ValidatableResponseOptions 的以下重载方法 −

  • time(matcher) - 它使用 Matcher 作为参数传递给方法,以毫秒为单位验证响应时间。
  • time(matcher, time unit) - 它使用 Matcher 验证响应时间,并将时间单位作为参数传递给方法。

我们将借助 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() {

      // 包含 Rest Assured 类的基本 URI
      RestAssured.baseURI ="https://www.tutorialspoint.com/index.htm";

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

      // GET 请求
      Response res = r.get();

      // 获取字符串形式的 Response
      String j = res.asString();

      // 获取 ValidatableResponse 类型
      ValidatableResponse v = res.then();

      //验证响应时间是否小于 1000 毫秒
      v.time(Matchers.lessThan(1000L));
   }
}

输出


相关文章