Unit testing, custom call class for retrofit2 request: Failure has private access

When I create my own call class, I cannot return a Response because the Response class is final. Is there a workaround for this?

public class TestCall implements Call<PlacesResults> { String fileType; String getPlacesJson = "getplaces.json"; String getPlacesUpdatedJson = "getplaces_updated.json"; public TestCall(String fileType) { this.fileType = fileType; } @Override public Response execute() throws IOException { String responseString; InputStream is; if (fileType.equals(getPlacesJson)) { is = InstrumentationRegistry.getContext().getAssets().open(getPlacesJson); } else { is = InstrumentationRegistry.getContext().getAssets().open(getPlacesUpdatedJson); } PlacesResults placesResults= new Gson().fromJson(new InputStreamReader(is), PlacesResults.class); //CAN"T DO IT return new Response<PlacesResults>(null, placesResults, null); } @Override public void enqueue(Callback callback) { } //default methods here //.... } 

In my unit test class, I want to use it as follows:

 Mockito.when(mockApi.getNearbyPlaces(eq("testkey"), Matchers.anyString(), Matchers.anyInt())).thenReturn(new TestCall("getplaces.json")); GetPlacesAction action = new GetPlacesAction(getContext().getContentResolver(), mockEventBus, mockApi, "testkey"); action.downloadPlaces(); 

My downloadPlaces () method looks like this:

 public void downloadPlaces() { Call<PlacesResults> call = api.getNearbyPlaces(webApiKey, LocationLocator.getInstance().getLastLocation(), 500); PlacesResults jsonResponse = null; try { Response<PlacesResults> response = call.execute(); Timber.d("response " + response); jsonResponse = response.body(); if (jsonResponse == null) { throw new IllegalStateException("Response is null"); } } catch (UnknownHostException e) { events.sendError(EventBus.ERROR_NO_CONNECTION); } catch (Exception e) { events.sendError(EventBus.ERROR_NO_PLACES); return; } //TODO: some database operations } 
0
java android unit-testing mockito retrofit2
Aug 19 '16 at 8:25
source share
1 answer

After a more thorough study of the Retfit2 Response class, I found that there is a static method that does what I need. So, I just changed this line:

 return new Response<PlacesResults>(null, placesResults, null); 

at

 return Response.success(placesResults); 

Now everything works.

+1
Aug 19 '16 at 11:10
source share



All Articles