Created
April 9, 2016 23:19
-
-
Save ktchernov/505b446e2dbaac9c765a6b2747653694 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.mydemoapp; | |
import org.junit.Before; | |
import org.junit.Rule; | |
import org.junit.Test; | |
import org.junit.rules.TestRule; | |
import org.junit.rules.Timeout; | |
import java.io.IOException; | |
import okhttp3.Call; | |
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.assertTrue; | |
public class OkHttpRetryTest { | |
@Rule public final MockWebServer server = new MockWebServer(); | |
private OkHttpClient client; | |
@Before | |
public void setUp() { | |
client = new OkHttpClient.Builder().retryOnConnectionFailure(true).build(); | |
} | |
@Test public void doNotRecoverPostAfterRequestWhenRetryOnConnectionFailureIsTrue() | |
throws Exception { | |
server.enqueue(new MockResponse().setBody("seed connection pool")); | |
server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AFTER_REQUEST)); | |
server.enqueue(new MockResponse().setBody("third call")); | |
assertTrue(client.retryOnConnectionFailure()); | |
RequestBody body = RequestBody.create(MediaType.parse("text/plain"), "Body"); | |
Request postRequest = new Request.Builder().url(server.url("/")).post(body).build(); | |
executeSynchronously(postRequest).assertBody("seed connection pool"); | |
executeSynchronously(postRequest).assertFailure(IOException.class); | |
executeSynchronously(postRequest).assertBody("third call"); | |
} | |
private RecordedResponse executeSynchronously(Request request) throws IOException { | |
Call call = client.newCall(request); | |
try { | |
Response response = call.execute(); | |
String bodyString = response.body().string(); | |
return new RecordedResponse(request, response, null, bodyString, null); | |
} catch (IOException e) { | |
return new RecordedResponse(request, null, null, null, e); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment