jck28-lucio-超时处理

超时处理简介

  • 超时处理的场景
  • 如何设置接口超时
    image

为什么需要请求超时处理

autonumber
scale 200 width
scale 400 height
participant 接口用例1 as case1
participant 接口用例2 as case2
participant 接口用例3 as case3
participant 服务端 as server

case1 -[#green]> server : 用例1发起请求
server -[#green]> case1 : 用例1收到响应
case2 -[#green]> server : 用例2发起请求
server → server !!: 服务端阻塞
case3 o-[#grey]> case3 : 等待用例2执行结束

设置请求超时的效果

autonumber
scale 200 width
scale 400 height
participant 接口用例1 as case1
participant 接口用例2 as case2
participant 接口用例3 as case3
participant 服务端 as server

case1 -[#green]> server : 用例1发起请求
server -[#green]> case1 : 用例1收到响应
case2 -[#green]> server : 用例2发起请求,超时时间3秒
server ->x server : 服务端响应超时
case2 → case2: 3秒后用例2终止请求
case3 -[#green]> server : 用例3发起请求
server -[#green]> case3: 用例3收到响应

设置超时时间

  • 创建 HttpClientConfig 实例
  • 创建 RestAssuredConfig 实例
  • given 语句中调用 config() 方法
@Test
void case2(){
    // 自定义HttpClientConfig对象
    // 设置响应超时时长为3秒,单位是毫秒
    HttpClientConfig clientConfig = HttpClientConfig
            .httpClientConfig()
            .setParam("http.socket.timeout", 3000);

    // 定义RestAssuredConfig对象
    // 传入自定义的HttpClientConfig对象
    RestAssuredConfig myTimeout = RestAssuredConfig
            .config()
            .httpClient(clientConfig);

    // 接口调用
    given().config(myTimeout).when().then();
}

设置超时时间

  • 完整示例
import io.restassured.RestAssured;
import io.restassured.config.HttpClientConfig;
import io.restassured.config.RestAssuredConfig;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;


public class TestTimeout {

    @BeforeAll
    static void setupClass(){
        RestAssured.baseURI = "https://httpbin.ceshiren.com";
    }

    @Test
    void case1() {
        given()
        .when()
                .get("/get")  // 发送GET请求
        .then()
                .statusCode(200);  // 响应断言
    }

    @Test
    void case2(){

        // 自定义HttpClientConfig对象
        // 设置响应超时时长为3秒,单位是毫秒
        HttpClientConfig clientConfig = HttpClientConfig
                .httpClientConfig()
                .setParam("http.socket.timeout", 3000);

        // 定义RestAssuredConfig对象
        // 传入自定义的HttpClientConfig对象
        RestAssuredConfig myTimeout = RestAssuredConfig
                .config()
                .httpClient(clientConfig);

        // 接口调用
        given()
                .config(myTimeout)  // 设置超时处理
        .when()
                .get("/delay/10")  // 特定接口,延迟10秒响应
        .then()
                .statusCode(200);  // 响应断言
    }

    @Test
    void case3(){
        given()
        .when()
                .get("/get")  // 发送GET请求
        .then()
                .statusCode(200);  // 响应断言
    }

}