原文链接

A 发送请求,然后等待 B 的响应,同时开始超时计时,如果在超时时间内成功接收到响应,则结束等待和计时。如果到了超时时间还没有接收到响应,则结束等待同时此次通讯失败,这个过程叫做请求超时。在接口自动化测试过程中,也常常会碰到请求超时的场景。

如下图所示,测试用例 2 没有设置超时处理,遇到服务端阻塞,测试用例 2 一直处于等待的状态,后面的测试用例都不执行:

接口不慢为什么请求超时(技术分享接口测试中)(1)

如下图所示,如果测试用例 2 设置了 3s 的超时时间,遇到服务端阻塞,测试用例 2 在 3s 之后则抛出异常,测试用例 3 正常执行:

接口不慢为什么请求超时(技术分享接口测试中)(2)

实战练习

编写三条测试用例,在 test_two 测试用例中设置超时时间为 3 秒,超过 3s 还没有得到响应的话则抛出异常,然后正常执行后面的测试用例。

Python 版本

Python 可以在调用请求方法时传入 timeout 参数控制超时时间。

import requests class TestReq: def test_one(self): r = requests.post("https://httpbin.ceshiren.com/post") assert r.status_code == 200 def test_two(self): # 通过timeout 参数设置超时时间,设置超时时间为0.1s,模拟超时场景 r = requests.post("https://github.com/post", timeout=0.1) assert r.status_code == 200 def test_three(self): r = requests.post("https://httpbin.ceshiren.com/post") assert r.status_code == 200

JAVA版本

Java 需要通过添加 RestAssured 的配置信息来处理超时的请求。通过 setParam() 设置超时时间,第一个参数为连接的类型,第二个参数为超时的最大时长,单位是 3000 毫秒。

import io.restassured.RestAssured; import io.restassured.config.HttpClientConfig; import io.restassured.config.RestAssuredConfig; import org.junit.jupiter.api.Test; import static io.restassured.RestAssured.given; public class ReqTimeoutTest { @Test void timeout1(){ given(). when().get("https://httpbin.ceshiren.com/get").then().statusCode(200).log().all(); } @Test void timeout2(){ RestAssured.config=RestAssuredConfig.config().httpClient(HttpClientConfig.httpClientConfig(). setParam("http.connection.timeout",3000). setParam("http.socket.timeout",3000). setParam("http.connection-manager.timeout",3000)); given().when().get("https://github.com/").then().log().all(); } @Test void timeout3(){ given().when().get("https://httpbin.ceshiren.com/get").then().statusCode(200).log().all(); } }

⬇️ 你好呀,喜欢这篇文章的话记得点个“赞”哦!大家的支持很重要~(*^▽^*) PS:有问题可以联系我们哦~v ceshiren001

>更多技术文章分享和免费资料领取

https://qrcode.ceba.ceshiren.com/link?name=article&project_id=qrcode&from=toutiao×tamp=1661131330&author=QY

,