Skip to content

Instantly share code, notes, and snippets.

@ktchernov
Created April 27, 2016 03:56
Show Gist options
  • Save ktchernov/fa5f6e16d128571bf9dfad7e7258512e to your computer and use it in GitHub Desktop.
Save ktchernov/fa5f6e16d128571bf9dfad7e7258512e 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 okhttp3.OkHttpClient;
import okhttp3.Request;
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;
public class OkHttpAbortedTest {
@Rule public final MockWebServer server = new MockWebServer();
private OkHttpClient client;
@Before
public void setUp() {
client = new OkHttpClient.Builder().build();
}
@Test public void whenRetryOnConnectionFailureIsFalse_getAfterDisconnectAtEndShouldSucceed()
throws Exception {
server.enqueue(new MockResponse().setBody("first call").setSocketPolicy(
SocketPolicy.DISCONNECT_AT_END));
server.enqueue(new MockResponse().setBody("second call"));
client = client.newBuilder().retryOnConnectionFailure(false).build();
Request postRequest = new Request.Builder().url(server.url("/")).get().build();
assertEquals("first call", executeSynchronously(postRequest).body().string());
assertEquals("second call", executeSynchronously(postRequest).body().string());
}
@Test public void whenRetryOnConnectionFailureIsTrue_getAfterDisconnectAtEndShouldSucceed()
throws Exception {
server.enqueue(new MockResponse().setBody("first call").setSocketPolicy(
SocketPolicy.DISCONNECT_AT_END));
server.enqueue(new MockResponse().setBody("second call"));
assertTrue(client.retryOnConnectionFailure());
Request postRequest = new Request.Builder().url(server.url("/")).get().build();
assertEquals("first call", executeSynchronously(postRequest).body().string());
assertEquals("second call", executeSynchronously(postRequest).body().string());
}
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