By default MockWebServer use a queue to specify a series of responses. These responses will be delivered to the client in sequential order.
How to customize the responses?
Using a dispatcher we can customize these responses.
Step 1: Define Dispatcher.
Dispatcher dispatcher = new Dispatcher() {
@Override
public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
switch (request.getPath()) {
case "/v1/welcome1":
return new MockResponse().setResponseCode(200).setBody("Good Morning");
case "/v1/app-details":
return new MockResponse().setResponseCode(200).setBody("version=9");
case "/v1/owner":
return new MockResponse().setResponseCode(200).setBody(json);
}
return new MockResponse().setResponseCode(404);
}
};
Step 2: Set the dispatcher to MockWebServer.
mockWebServer.setDispatcher(dispatcher);
Find the below working application.
SimpleRestClient.java
package com.sample.app;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
public class SimpleRestClient {
private String url;
public SimpleRestClient(String url) {
this.url = url;
}
public String getRequest() throws ClientProtocolException, IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet(url);
return getResponseAsString(httpclient.execute(httpget));
}
public CloseableHttpResponse getClosebaleResponse() throws ClientProtocolException, IOException {
HttpRequestBase httpget = new HttpGet(url);
CloseableHttpClient httpclient = HttpClients.createDefault();
return httpclient.execute(httpget);
}
public String maxConnTimeOut(int noOfSeconds) throws ClientProtocolException, IOException {
RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
requestConfigBuilder.setConnectTimeout(noOfSeconds * 1000);
requestConfigBuilder.setConnectionRequestTimeout(noOfSeconds * 1000);
requestConfigBuilder.setSocketTimeout(noOfSeconds * 1000);
RequestConfig requestConfig = requestConfigBuilder.build();
HttpRequestBase httpget = new HttpGet(url);
httpget.setConfig(requestConfig);
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse httpResponse = httpclient.execute(httpget);
return getResponseAsString(httpResponse);
}
public void postAndIgnore() throws ClientProtocolException, IOException {
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("name", "Krishna"));
formparams.add(new BasicNameValuePair("password", "password"));
formparams.add(new BasicNameValuePair("mailId", "abcdef@abcdef.com"));
UrlEncodedFormEntity requestBody = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
HttpPost httppost = new HttpPost(url + "?appName=chatserver");
httppost.setEntity(requestBody);
try (CloseableHttpClient httpclient = HttpClientBuilder.create().build();) {
httpclient.execute(httppost);
}
}
public static String getResponseAsString(InputStream is) throws IOException {
try (InputStreamReader isReader = new InputStreamReader(is)) {
BufferedReader reader = new BufferedReader(isReader);
StringBuffer sb = new StringBuffer();
String str;
while ((str = reader.readLine()) != null) {
sb.append(str);
}
return sb.toString();
}
}
public static String getResponseAsString(CloseableHttpResponse closeableHttpResponse)
throws UnsupportedOperationException, IOException {
HttpEntity httpEntity = closeableHttpResponse.getEntity();
return getResponseAsString(httpEntity.getContent());
}
}
HelloWorldTest.java
package mockwebserver;
import static org.junit.Assert.assertThrows;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.util.concurrent.TimeUnit;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.junit.jupiter.api.Test;
import com.sample.app.SimpleRestClient;
import okhttp3.HttpUrl;
import okhttp3.mockwebserver.Dispatcher;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
public class HelloWorldTest {
@Test
public void hello() throws IOException {
try (MockWebServer mockWebServer = new MockWebServer();) {
String msg1 = "Good Morning";
String msg2 = "Good Afternoon";
String msg3 = "Good Evening";
mockWebServer.enqueue(new MockResponse().setBody(msg1));
mockWebServer.enqueue(new MockResponse().setBody(msg2));
mockWebServer.enqueue(new MockResponse().setBody(msg3));
mockWebServer.start(1234);
HttpUrl baseUrl = mockWebServer.url("/v1/welcome");
SimpleRestClient simpleRestClient = new SimpleRestClient(baseUrl.toString());
String body1 = simpleRestClient.getRequest();
assertEquals(msg1, body1);
String body2 = simpleRestClient.getRequest();
assertEquals(msg2, body2);
String body3 = simpleRestClient.getRequest();
assertEquals(msg3, body3);
mockWebServer.shutdown();
}
}
@Test
public void urlRedirection() throws IOException {
try (MockWebServer mockWebServer = new MockWebServer();) {
mockWebServer.start(1234);
mockWebServer.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
.addHeader("Location: " + mockWebServer.url("/new-path")).setBody("This page has moved!"));
mockWebServer.enqueue(new MockResponse().setBody("This is the new location!"));
HttpUrl baseUrl = mockWebServer.url("/v1/welcome");
SimpleRestClient simpleRestClient = new SimpleRestClient(baseUrl.toString());
CloseableHttpResponse httpResponse = simpleRestClient.getClosebaleResponse();
int statusCode = httpResponse.getStatusLine().getStatusCode();
String body = SimpleRestClient.getResponseAsString(httpResponse);
assertEquals(200, statusCode);
assertEquals("This is the new location!", body);
mockWebServer.shutdown();
}
}
@Test
public void delayResponseTime() throws IOException {
try (MockWebServer mockWebServer = new MockWebServer();) {
mockWebServer.start(1234);
mockWebServer.enqueue(new MockResponse().setBody("Hello World").setBodyDelay(5, TimeUnit.SECONDS));
HttpUrl baseUrl = mockWebServer.url("/v1/welcome");
SimpleRestClient simpleRestClient = new SimpleRestClient(baseUrl.toString());
Throwable exception = assertThrows(SocketTimeoutException.class, () -> {
String response = simpleRestClient.maxConnTimeOut(2);
assertEquals("Hello World", response);
});
assertEquals("Read timed out", exception.getMessage());
mockWebServer.shutdown();
}
}
@Test
public void validateRequestBody() throws IOException, InterruptedException {
try (MockWebServer mockWebServer = new MockWebServer();) {
mockWebServer.start(1234);
mockWebServer.enqueue(new MockResponse().setBody("Hello World"));
HttpUrl baseUrl = mockWebServer.url("/v1/welcome");
SimpleRestClient simpleRestClient = new SimpleRestClient(baseUrl.toString());
simpleRestClient.postAndIgnore();
RecordedRequest recordedRequest = mockWebServer.takeRequest();
assertEquals("POST", recordedRequest.getMethod());
assertEquals("name=Krishna&password=password&mailId=abcdef%40abcdef.com",
recordedRequest.getBody().readUtf8());
assertEquals("application/x-www-form-urlencoded; charset=UTF-8", recordedRequest.getHeader("Content-Type"));
HttpUrl httpUrl = recordedRequest.getRequestUrl();
assertEquals("http://localhost:1234/v1/welcome?appName=chatserver", httpUrl.toString());
mockWebServer.shutdown();
}
}
@Test
public void customizeResponses() throws IOException, InterruptedException {
String json = "{\"org\": \"abc_org\", \"location\": \"India\"}";
try (MockWebServer mockWebServer = new MockWebServer();) {
mockWebServer.start(1234);
Dispatcher dispatcher = new Dispatcher() {
@Override
public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
switch (request.getPath()) {
case "/v1/welcome1":
return new MockResponse().setResponseCode(200).setBody("Good Morning");
case "/v1/app-details":
return new MockResponse().setResponseCode(200).setBody("version=9");
case "/v1/owner":
return new MockResponse().setResponseCode(200).setBody(json);
}
return new MockResponse().setResponseCode(404);
}
};
mockWebServer.setDispatcher(dispatcher);
SimpleRestClient simpleRestClient = new SimpleRestClient("http://localhost:1234/v1/app-details");
String resp = simpleRestClient.getRequest();
assertEquals("version=9", resp);
mockWebServer.shutdown();
}
}
}
junit output
You can download the complete working application from below link.
https://github.com/harikrishna553/java-libs/tree/master/okhttp3/mockwebserver/mockwebserver-demo
Previous Next Home
No comments:
Post a Comment