Skip to content

Instantly share code, notes, and snippets.

@apottere
Last active February 13, 2018 19:12
Show Gist options
  • Save apottere/93e89c7645c1b2e9f97402b10507d574 to your computer and use it in GitHub Desktop.
Save apottere/93e89c7645c1b2e9f97402b10507d574 to your computer and use it in GitHub Desktop.
package com.dealer.webplatform.pageservice;
import com.squareup.okhttp.mockwebserver.MockResponse;
import com.squareup.okhttp.mockwebserver.MockWebServer;
import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import java.io.IOException;
import java.nio.file.Files;
import static org.junit.Assert.*;
public class OkHttpTest {
@Rule
public final MockWebServer server = new MockWebServer();
private OkHttpClient client;
@Before
public void setup() throws IOException {
client = new OkHttpClient.Builder()
.cache(new Cache(Files.createTempDirectory("ok-http").toFile(), 10485760))
.build();
}
@After
public void cleanup() throws IOException {
client.cache().close();
}
@Test
public void requestWithoutQueryValidatesETag() throws IOException {
Request request = createRequest("/path");
server.enqueue(createMockResponse().setResponseCode(200));
server.enqueue(createMockResponse().setResponseCode(304));
Response response = client.newCall(request).execute();
response.close();
Response response2 = client.newCall(request).execute();
response2.close();
assertEquals("cached request was not returned", response.code(), response2.code());
assertEquals("server did not receive two requests", server.getRequestCount(), 2);
}
@Test
public void requestWithQueryValidatesETag() throws IOException {
Request request = createRequest("/path?a");
server.enqueue(createMockResponse().setResponseCode(200));
server.enqueue(createMockResponse().setResponseCode(304));
Response response = client.newCall(request).execute();
response.close();
Response response2 = client.newCall(request).execute();
response2.close();
assertEquals("cached request was not returned", response.code(), response2.code());
assertEquals("server did not receive two requests", server.getRequestCount(), 2);
}
private MockResponse createMockResponse() {
return new MockResponse()
.addHeader("ETag", "\"not-used\"")
.addHeader("Last-Modified" , "Sat, 10 Feb 2018 10:00:00 GMT");
}
private Request createRequest(String path) {
return new Request.Builder()
.url(server.url(path).url())
.build();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment