Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactoring tests to make use of shared code #90

Merged
merged 1 commit into from
May 8, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
217 changes: 118 additions & 99 deletions src/test/java/com/recurly/v3/BaseClientTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,15 @@
import com.recurly.v3.fixtures.MyRequest;
import com.recurly.v3.fixtures.MyResource;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

import org.apache.commons.io.IOUtils;
import org.joda.time.DateTime;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
import org.mockito.stubbing.Answer;

import java.io.IOException;
import java.io.InputStream;
Expand All @@ -25,79 +26,142 @@
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

@SuppressWarnings("unchecked")
public class BaseClientTest {

@Test
public void testMakeRequestWithResource() {
OkHttpClient mockOkHttpClient = getMockOkHttpClient(getResponseJson());
public void testMakeRequestWithResource() throws IOException {
final Call mCall = mock(Call.class);
Answer answer = (i) -> {
Request request = i.getArgument(0);
HttpUrl url = request.url();
assertEquals("GET", request.method());
assertEquals("/resources/code-aaron", url.url().getPath());
return mCall;
};
when(mCall.execute()).thenReturn(MockClient.buildResponse(200, "OK", getResponseJson()));

OkHttpClient mockOkHttpClient = MockClient.getMockOkHttpClient(answer);

final MockClient client = new MockClient("apiKey", mockOkHttpClient);
final MyResource resource = client.getResource("code-aaron");

// TODO: Verify the request made was correct. MockWebServer?
assertEquals(MyResource.class, resource.getClass());
}

@Test
public void testMakeRequestWithBody() {
OkHttpClient mockOkHttpClient = getMockOkHttpClient(getResponseJson());
public void testMakeRequestWithBody() throws IOException {
final Call mCall = mock(Call.class);
AtomicBoolean postCalled = new AtomicBoolean(false);
AtomicBoolean putCalled = new AtomicBoolean(false);
Answer answer = (i) -> {
Request request = i.getArgument(0);
HttpUrl url = request.url();
switch (request.method()) {
case "POST":
assertEquals("/resources", url.url().getPath());
postCalled.set(true);
break;
case "PUT":
assertEquals("/resources/someId", url.url().getPath());
putCalled.set(true);
break;
default:
// Any other request method is a failure
Assert.fail();
}
return mCall;
};
when(mCall.execute())
.thenReturn(MockClient.buildResponse(200, "OK", getResponseJson()))
.thenReturn(MockClient.buildResponse(200, "OK", getResponseJson()));

OkHttpClient mockOkHttpClient = MockClient.getMockOkHttpClient(answer);

final MockClient client = new MockClient("apiKey", mockOkHttpClient);
final MyRequest newResource = new MyRequest();
newResource.setMyString("aaron");
final MyResource resource = client.createResource(newResource);

// TODO: Verify the request made was correct. MockWebServer?
final MyResource resource = client.createResource(newResource);
assertEquals(MyResource.class, resource.getClass());
assertEquals("aaron", resource.getMyString());
assertTrue(postCalled.get());

// Ensure that update works as well
final MyResource anotherResource = client.updateResource("someId", newResource);
assertEquals(MyResource.class, anotherResource.getClass());
assertEquals("aaron", anotherResource.getMyString());
assertTrue(putCalled.get());
}

@Test
public void testMakeRequestWithoutResource() {
OkHttpClient mockOkHttpClient = getMockOkHttpClient("");
public void testMakeRequestWithoutResource() throws IOException {
final Call mCall = mock(Call.class);
Answer answer = (i) -> {
Request request = i.getArgument(0);
HttpUrl url = request.url();
assertEquals("DELETE", request.method());
assertEquals("/resources/resource-id", url.url().getPath());
return mCall;
};
when(mCall.execute()).thenReturn(MockClient.buildResponse(200, "OK", ""));

OkHttpClient mockOkHttpClient = MockClient.getMockOkHttpClient(answer);

final MockClient client = new MockClient("apiKey", mockOkHttpClient);
client.removeResource("resource-id");

// TODO: Verify the request made was correct. MockWebServer?
}

@Test
public void testMakeRequestWithQueryParams() {
OkHttpClient mockOkHttpClient = getMockOkHttpClient(getResponseListJson());
public void testMakeRequestWithQueryParams() throws IOException {
DateTime dateTime = new DateTime();

final Call mCall = mock(Call.class);
Answer answer = (i) -> {
Request request = i.getArgument(0);
HttpUrl url = request.url();
assertEquals("Aaron", url.queryParameter("my_string"));
assertEquals(dateTime.toString(), url.queryParameter("my_date_time"));
assertEquals("1", url.queryParameter("my_integer"));
assertEquals("2.3", url.queryParameter("my_float"));
assertEquals("4.5", url.queryParameter("my_double"));
assertEquals("6", url.queryParameter("my_long"));
assertEquals(null, url.queryParameter("my_random"));
assertEquals("[]", url.queryParameter("unsupported"));
return mCall;
};
when(mCall.execute()).thenReturn(MockClient.buildResponse(200, "OK", getResponseListJson()));

OkHttpClient mockOkHttpClient = MockClient.getMockOkHttpClient(answer);

final MockClient client = new MockClient("apiKey", mockOkHttpClient);
final MockQueryParams qp = new MockQueryParams();
qp.setMyString("Aaron");
qp.setMyDateTime(new DateTime());
qp.setMyDateTime(dateTime);
qp.setMyInteger(1);
qp.setMyFloat(2.3f);
qp.setMyDouble(4.5);
qp.setMyLong(6L);
qp.setMyRandom(null);
qp.setUnsupported(new ArrayList());
qp.setUnsupported(new ArrayList<>());
final Pager<MyResource> pager = client.listResources(qp);
pager.getNextPage();

// Todo: Assert that the query params all made it into the request
}

@Test
public void testNotFoundError() {
OkHttpClient mockOkHttpClient = getApiErrorMockOkHttpClient(getErrorJson("not_found"));
public void testNotFoundError() throws IOException {
final Call mCall = mock(Call.class);
Answer answer = (i) -> { return mCall; };
when(mCall.execute()).thenReturn(MockClient.buildResponse(404, "Not Found", getErrorJson("not_found")));

OkHttpClient mockOkHttpClient = MockClient.getMockOkHttpClient(answer);

final MockClient client = new MockClient("apiKey", mockOkHttpClient);

Expand All @@ -109,8 +173,12 @@ public void testNotFoundError() {
}

@Test
public void testValidationError() {
OkHttpClient mockOkHttpClient = getApiErrorMockOkHttpClient(getErrorResponse("validation"));
public void testValidationError() throws IOException {
final Call mCall = mock(Call.class);
Answer answer = (i) -> { return mCall; };
when(mCall.execute()).thenReturn(MockClient.buildResponse(422, "Unprocessable Entity", getErrorResponse("validation")));

OkHttpClient mockOkHttpClient = MockClient.getMockOkHttpClient(answer);

final MockClient client = new MockClient("apiKey", mockOkHttpClient);

Expand All @@ -122,8 +190,12 @@ public void testValidationError() {
}

@Test
public void testTransactionError() {
OkHttpClient mockOkHttpClient = getApiErrorMockOkHttpClient(getErrorResponse("transaction"));
public void testTransactionError() throws IOException {
final Call mCall = mock(Call.class);
Answer answer = (i) -> { return mCall; };
when(mCall.execute()).thenReturn(MockClient.buildResponse(422, "Unprocessable Entity", getErrorResponse("transaction")));

OkHttpClient mockOkHttpClient = MockClient.getMockOkHttpClient(answer);

final MockClient client = new MockClient("apiKey", mockOkHttpClient);

Expand All @@ -136,8 +208,12 @@ public void testTransactionError() {
}

@Test
public void testNetworkError() {
OkHttpClient mockOkHttpClient = getNetworkErrorMockOkHttpClient();
public void testNetworkError() throws IOException {
final Call mCall = mock(Call.class);
Answer answer = (i) -> { return mCall; };
when(mCall.execute()).thenThrow(new IOException());

OkHttpClient mockOkHttpClient = MockClient.getMockOkHttpClient(answer);

final MockClient client = new MockClient("apiKey", mockOkHttpClient);
assertThrows(
Expand All @@ -148,8 +224,12 @@ public void testNetworkError() {
}

@Test
public void testNetworkErrorWithoutResource() {
OkHttpClient mockOkHttpClient = getNetworkErrorMockOkHttpClient();
public void testNetworkErrorWithoutResource() throws IOException {
final Call mCall = mock(Call.class);
Answer answer = (i) -> { return mCall; };
when(mCall.execute()).thenThrow(new IOException());

OkHttpClient mockOkHttpClient = MockClient.getMockOkHttpClient(answer);

final MockClient client = new MockClient("apiKey", mockOkHttpClient);
assertThrows(
Expand All @@ -160,8 +240,12 @@ public void testNetworkErrorWithoutResource() {
}

@Test
public void testBadMethodError() {
OkHttpClient mockOkHttpClient = getNetworkErrorMockOkHttpClient();
public void testBadMethodError() throws IOException {
final Call mCall = mock(Call.class);
Answer answer = (i) -> { return mCall; };
when(mCall.execute()).thenThrow(new IOException());

OkHttpClient mockOkHttpClient = MockClient.getMockOkHttpClient(answer);

final MockClient client = new MockClient("apiKey", mockOkHttpClient);

Expand Down Expand Up @@ -263,71 +347,6 @@ protected static void setEnv(Map<String, String> newenv) throws Exception {
}
}

private static OkHttpClient getMockOkHttpClient(String response) {
final OkHttpClient mockOkHttpClient = mock(OkHttpClient.class);
final Call mCall = mock(Call.class);
final Request mRequest = new Request.Builder().url("https://api.recurly.com").build();

final Response mResponse =
new Response.Builder()
.request(mRequest)
.protocol(okhttp3.Protocol.HTTP_1_1)
.code(200) // status code
.message("Created")
.body(ResponseBody.create(MediaType.get("application/json; charset=utf-8"), response))
.build();

final Response mResponse2 =
new Response.Builder()
.request(mRequest)
.protocol(okhttp3.Protocol.HTTP_1_1)
.code(200) // status code
.message("updated")
.body(ResponseBody.create(MediaType.get("application/json; charset=utf-8"), response))
.build();
when(mockOkHttpClient.newCall(any())).thenReturn(mCall);
try {
when(mCall.execute()).thenReturn(mResponse).thenReturn(mResponse2);
} catch (IOException e) {
e.printStackTrace();
}
return mockOkHttpClient;
}

private static OkHttpClient getApiErrorMockOkHttpClient(String response) {
final OkHttpClient mockOkHttpClient = mock(OkHttpClient.class);
final Call mCall = mock(Call.class);
final Request mRequest = new Request.Builder().url("https://api.recurly.com").build();

final Response mResponse =
new Response.Builder()
.request(mRequest)
.protocol(okhttp3.Protocol.HTTP_1_1)
.code(404) // status code
.message("Not Found")
.body(ResponseBody.create(MediaType.get("application/json; charset=utf-8"), response))
.build();
when(mockOkHttpClient.newCall(any())).thenReturn(mCall);
try {
when(mCall.execute()).thenReturn(mResponse);
} catch (IOException e) {
e.printStackTrace();
}
return mockOkHttpClient;
}

private static OkHttpClient getNetworkErrorMockOkHttpClient() {
final OkHttpClient mockOkHttpClient = mock(OkHttpClient.class);
final Call mCall = mock(Call.class);
when(mockOkHttpClient.newCall(any())).thenReturn(mCall);
try {
when(mCall.execute()).thenThrow(new IOException());
} catch (IOException e) {
e.printStackTrace();
}
return mockOkHttpClient;
}

private static String getResponseJson() {
return "{ \"my_string\": \"aaron\" }";
}
Expand Down
Loading