I've got a recursive method which uses okhttp3
to make consecutive paging requests to an endpoint until an attribute is no longer there. My tests run that simulate the last call in the process but I'm having trouble working through a 2 step iteration.
How do I define a specific ohkttp3.Request in the newCall() method so it doesn;t throw a NullPointer each time? My code/test is below for reference.
Error: java.lang.NullPointerException
Recursive Method
public JSONArray recursiveMethod(JSONArray array, String authCode, String requestUrl) {
String nextPageAtt = "newPage";
String newPage = null;
Request request = new Request.Builder()
.url(requestUrl)
.get()
.addHeader("Content-Type", "application/json")
.addHeader("Authorization", authCode)
.build();
try {
//Problem child
okhttp3.Response response = client.newCall(request).execute();
if (response.code() == SUCCESS_CODE && response.body() != null) {
//Add JSON data to array
//if "newPage" attribute in response, set it here
//only present when page != last page
} else {
}
}
//"newPage" attribute won't be present on the last page of data"
if (newPage != null) {
recursiveMethod(array, authCode, baseUrl + newPage);
}
return array;
}
Test Method
@Test
void recursiveMethodNonewPage() throws IOException {
JSONArray emptyArray = new JSONArray();
final Response successResponse = new Response.Builder()
.request(new Request.Builder().url("https://localhost:8080/getData").build()) //"newPage" not there (last call)
.protocol(Protocol.HTTP_1_1)
.code(SUCCESS_CODE).message("").body(
ResponseBody.create(
MediaType.parse("application/json"),
"/////JSON/////"
))
.build();
when(remoteCall.execute()).thenReturn(successResponse);
//this works when I pass "any()" but a java.lang.NullPointerException is thrown when I enter a specific Request
when(mockClient.newCall(any())).thenReturn(remoteCall);
//******Issue******
//Need to pass a specific request on in order to simulate multiple recursive iterations
/*Request request = new Request.Builder()
.url(https://localhost:8080/getData)
.get()
.addHeader("Content-Type", "application/json")
.addHeader("Authorization", authCode)
.build();*/
//Throws Null
//when(mockClient.newCall(request))).thenReturn(remoteCall);
JSONArray newArray = getDataUtil.recursiveMethod(emptyArray, authCodeSuccess, "https://localhost:8080/getData");
assertEquals(4, newArray.length());
}