Using ‘takeRequest’ method of MockWebServer, we can validate request parameters, body, request path and headers.
'takeRequest' method awaits the next HTTP request (waiting up to the specified wait time if necessary), removes it, and returns it.
Below step-by-step procedure explains how to validate request body.
Step 1: Get an instance of MockWebServer and start the mock server on port 1234.
MockWebServer mockWebServer = new MockWebServer();
mockWebServer.start(1234);
Step 2: Enqueue some mock response.
mockWebServer.enqueue(new MockResponse().setBody("Hello World"));
Step 3: Take the new request and validate the request payload.
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"));
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.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();
}
}
}
Junit output
You can download the complete working application from below link.
https://github.com/harikrishna553/java-libs/tree/master/okhttp3/mockwebserver/mockwebserver-demo
No comments:
Post a Comment