Skip to content

Instantly share code, notes, and snippets.

@ktchernov
Last active April 10, 2016 06:31
Show Gist options
  • Save ktchernov/5785e6d6664a9f306c01632b95492fdd to your computer and use it in GitHub Desktop.
Save ktchernov/5785e6d6664a9f306c01632b95492fdd to your computer and use it in GitHub Desktop.
package com.example.mydemoapp;
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 okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.SocketPolicy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class OkHttp3RetryTest {
@Rule public final MockWebServer server = new MockWebServer();
private OkHttpClient client;
@Before
public void setUp() {
client = new OkHttpClient.Builder().build();
}
@Test public void doNotRecoverPostAfterRequestWhenRetryOnConnectionFailureIsTrue()
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 = client.newBuilder().readTimeout(250, TimeUnit.MILLISECONDS).build();
assertTrue(client.retryOnConnectionFailure());
RequestBody body = RequestBody.create(MediaType.parse("text/plain"), "Body");
Request postRequest = new Request.Builder().url(server.url("/")).post(body).build();
assertEquals("seed connection pool", executeSynchronously(postRequest).body().string());
try {
executeSynchronously(postRequest).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