为okhttp超时写单元测试

时间:2021-06-20 23:15:56

I have written test case for okHttp SocketTimeoutException like this:

我已经为okHttp SocketTimeoutException编写了测试用例,如下所示:

    @Test
    public void contactDetailsTimeOut() throws Exception {
    server.enqueue(new MockResponse().setBody("{}").setBodyDelay(31, TimeUnit.SECONDS));

    HttpUrl baseUrl = server.url("/v1/contact/");
    userProfilePresenter.contactDetails(baseUrl.toString());
    verify(userProfileView).error(isA(SocketTimeoutException.class), isA(String.class));
    }

Same can be achieved by setting setSocketPolicy to SocketPolicy.NO_RESPONSE

通过将setSocketPolicy设置为SocketPolicy.NO_RESPONSE可以实现相同

    @Test
    public void contactDetailsTimeOut() throws Exception {
    server.enqueue(new MockResponse().setBody("{}").setSocketPolicy(SocketPolicy.NO_RESPONSE));

    HttpUrl baseUrl = server.url("/v1/contact/");
    userProfilePresenter.contactDetails(baseUrl.toString());
    verify(userProfileView).error(isA(SocketTimeoutException.class), isA(String.class));
    }

As i have set okHttp readTimeout to 30 sec. This test case wait for 30 sec to pass. Expected behaviour. Below is the code of okHttpClient

因为我已将okHttp readTimeout设置为30秒。此测试用例等待30秒通过。预期的行为。下面是okHttpClient的代码

private static OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .readTimeout(30, TimeUnit.SECONDS)
            .build();

My question is: Is there any way i can test SocketTimeoutException in less time? I do not want to reduce timing from client side.

我的问题是:有没有办法可以在更短的时间内测试SocketTimeoutException?我不想减少客户端的时间安排。

1 个解决方案

#1


0  

You can create a custom OkHttpClient in singleton pattern, and then you can prepare it in the setup() in unit test.

您可以以单例模式创建自定义OkHttpClient,然后可以在单元测试中的setup()中进行准备。

#1


0  

You can create a custom OkHttpClient in singleton pattern, and then you can prepare it in the setup() in unit test.

您可以以单例模式创建自定义OkHttpClient,然后可以在单元测试中的setup()中进行准备。