Unit testing, custom Call class for retrofit2 request: Reponse has private access

谁说我不能喝 提交于 2019-12-23 05:23:55

问题


When I create custom Call class I can't return Response, because Response class is final. Is there any 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 like this:

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 look like:

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
}

回答1:


After looking at retrofit2 Response class more thoroughly I've found out that there is a static method that do what I need. So, I simply changed this line:

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

to:

return Response.success(placesResults);

Everything works now.



来源:https://stackoverflow.com/questions/39034404/unit-testing-custom-call-class-for-retrofit2-request-reponse-has-private-acces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!