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);
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; }
java android unit-testing mockito retrofit2
zkvarz Aug 19 '16 at 8:25 2016-08-19 08:25
source share