如何在 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.com/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));
}
}输出

广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP