Write unit test for okhttp timeout

Viewed 1296

I have written test case for okHttp SocketTimeoutException like this:

    @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

    @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

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.

1 Answers

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

Related