okhttp+mockwebserver
okhttp https://github.com/square/okhttp
mockwebserver https://github.com/square/okhttp/tree/master/mockwebserver
Android界隈向けでよく名前出てくるokhttp、と同等なプロジェクトグループ?が開発しているmockwebserverを使ってみた
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.mockwebserver.Dispatcher;
import com.squareup.okhttp.mockwebserver.MockResponse;
import com.squareup.okhttp.mockwebserver.MockWebServer;
import com.squareup.okhttp.mockwebserver.RecordedRequest;
import org.junit.After;
import org.junit.Test;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;
public class MainTest {
private MockWebServer server = new MockWebServer();
@After
public void tearDown() throws IOException {
server.shutdown();
}
@Test
public void test1() throws IOException {
server.setDispatcher(new Dispatcher() {
@Override
public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
return new MockResponse().setBody("test1");
}
});
server.play();
Request request = new Request.Builder()
.url("http://kinjouj.github.io")
.build();
OkHttpClient client = new OkHttpClient();
client.setProxy(
new Proxy(
Proxy.Type.HTTP,
new InetSocketAddress(server.getHostName(), server.getPort())
)
);
Response response = client.newCall(request).execute();
assertThat(response.isSuccessful(), is(true));
assertThat(response.body().string(), is("test1"));
}
@Test
public void test2() throws IOException {
server.setDispatcher(new Dispatcher() {
@Override
public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
MockResponse response = null;
if (request.getPath().equals("/test2")) {
response = new MockResponse().setBody("test2");
} else {
response = new MockResponse().setStatus("HTTP/1.1 404 Not Found");
}
return response;
}
});
server.play();
OkHttpClient client = new OkHttpClient();
Request request1 = new Request.Builder()
.url(server.getUrl("/test2"))
.build();
Response response1 = client.newCall(request1).execute();
assertThat(response1.isSuccessful(), is(true));
assertThat(response1.body().string(), is("test2"));
Request request2 = new Request.Builder()
.url(server.getUrl("/test1"))
.build();
Response response2 = client.newCall(request2).execute();
assertThat(response2.code(), is(200)); // fail
}
}
てな感じでMockWebServerを使って起動して返すレスポンスをMockResponseで返す。それをOkHttpClientで取得してテストみたいなまぁ適当なパターン。でtest1では外部へリクエストするけど、MockWebServerをプロキシとして利用してレスポンスを擬似的に返してテストしたりとか出来る?んじゃないかと
んまぁそういう面でも利用も出来なくもないんじゃないかと