Tuesday 6 July 2021

MockWebServer: url redirection

In this post, I am going to explain how to mock url redirection scenario using MockWebServer.

 

Step 1: Define and start MockWebServer.

MockWebServer mockWebServer = new MockWebServer();
mockWebServer.start(1234);

 

Step 2: Enqueue a redirection response.

mockWebServer.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP).addHeader("Location: " + mockWebServer.url("/new-path")).setBody("This page has moved!"));

 

When client hits the mock server for the first time, mock server respond with 302 status code and new location information (Which specifies where to redirect).

 

Enqueue another response to validate whether our client app is working fine or not.

mockWebServer.enqueue(new MockResponse().setBody("This is the new location!"));

 

Step 3: Test the client application.

HttpUrl baseUrl = mockWebServer.url("/v1/welcome");

SimpleRestClient simpleRestClient = new SimpleRestClient(baseUrl.toString());

CloseableHttpResponse httpResponse = simpleRestClient.getRespEntity();

int statusCode = httpResponse.getStatusLine().getStatusCode();
String body = SimpleRestClient.getResponseAsString(httpResponse);

assertEquals(200, statusCode);
assertEquals("This is the new location!", body);

 

Step 4: shutdown mock webserver.

mockWebServer.shutdown();

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 org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

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 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.jupiter.api.Assertions.assertEquals;

import java.io.IOException;
import java.net.HttpURLConnection;

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;

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();
		}

	}

}




You can download 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