Skip to content

Instantly share code, notes, and snippets.

@ktchernov
Last active January 17, 2017 03:52
Show Gist options
  • Save ktchernov/2a1b6ad8a0b0f12634a55b9e2551395e to your computer and use it in GitHub Desktop.
Save ktchernov/2a1b6ad8a0b0f12634a55b9e2551395e to your computer and use it in GitHub Desktop.
package com.example.mydemoapp;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.mockwebserver.MockResponse;
import com.squareup.okhttp.mockwebserver.MockWebServer;
import com.squareup.okhttp.mockwebserver.SocketPolicy;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class OkHttp2RetryTest {
@Rule public final MockWebServer server = new MockWebServer();
private OkHttpClient client;
@Before
public void setUp() {
client = new OkHttpClient();
}
@Test public void recoverWhenRetryOnConnectionFailureIsTrue() throws Exception {
server.enqueue(new MockResponse().setBody("seed connection pool"));
server.enqueue(new MockResponse().setBody("second call")
.setSocketPolicy(SocketPolicy.NO_RESPONSE));
server.enqueue(new MockResponse().setBody("third call"));
client.setReadTimeout(250, TimeUnit.MILLISECONDS);
assertTrue(client.getRetryOnConnectionFailure());
RequestBody body = RequestBody.create(MediaType.parse("text/plain"), "Body");
Request request = new Request.Builder().url(server.url("/")).post(body).build();
assertEquals("seed connection pool", executeSynchronously(request).body().string());
try {
executeSynchronously(request).body().string();
fail();
} catch (InterruptedIOException e) {
}
}
private Response executeSynchronously(Request request) throws IOException {
return client.newCall(request).execute();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment