在 REST Assured 中,如何设置超时?

In REST Assured, how do I set a timeout?

我正在使用 RestAssured 2.8.0 我正在尝试设置自己的超时(用于网关超时), 所以如果我在 X 毫秒后没有得到响应我想中止。

我试过了:

public static ValidatableResponse postWithConnectionConfig(String url, String body, RequestSpecification requestSpecification, ResponseSpecification responseSpecification) {
    ConnectionConfig.CloseIdleConnectionConfig closeIdleConnectionConfig = new ConnectionConfig.CloseIdleConnectionConfig(1L, TimeUnit.MILLISECONDS);
    ConnectionConfig connectionConfig = new ConnectionConfig(closeIdleConnectionConfig);
    RestAssuredConfig restAssuredConfig = new RestAssuredConfig().connectionConfig(connectionConfig);


    return given().specification(requestSpecification)
            .body(body)
            .config(restAssuredConfig)
            .post(url)
            .then()
            .specification(responseSpecification);

}

ConnectionConfig connectionConfig = new ConnectionConfig()
            .closeIdleConnectionsAfterEachResponseAfter(10L, TimeUnit.MILLISECONDS);
RestAssuredConfig restAssuredConfig = new RestAssuredConfig().connectionConfig(connectionConfig);

我也尝试添加

.queryParam("SO_TIMEOUT", 10)

.queryParam("CONNECTION_MANAGER_TIMEOUT", 10)

似乎没有任何效果。 它不会中止我的查询

您可以通过设置 HTTP 客户端参数来配置超时:

RestAssuredConfig config = RestAssured.config()
        .httpClient(HttpClientConfig.httpClientConfig()
                .setParam(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000)
                .setParam(CoreConnectionPNames.SO_TIMEOUT, 1000));

given().config(config).post("http://localhost:8884");

由于 CoreConnectionPNames 已被弃用,这里有一个更新的方法。这适用于 Apache HTTP 客户端 4.5.3:

import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.HttpClientBuilder;

import io.restassured.RestAssured;
import io.restassured.config.HttpClientConfig;

...

RequestConfig requestConfig = RequestConfig.custom()
    .setConnectTimeout(5000)
    .setConnectionRequestTimeout(5000)
    .setSocketTimeout(5000)
    .build();

HttpClientConfig httpClientFactory = HttpClientConfig.httpClientConfig()
    .httpClientFactory(() -> HttpClientBuilder.create()
        .setDefaultRequestConfig(requestConfig)
        .build());

RestAssured.config = RestAssured
    .config()
    .httpClient(httpClientFactory);

以下配置对我有用。

RestAssured.config=RestAssuredConfig.config()
                        .httpClient(HttpClientConfig.httpClientConfig()
                                .setParam("http.socket.timeout",1000)
                                .setParam("http.connection.timeout", 1000));