响应具有私有访问权限

响应具有私有访问权限

本文介绍了单元测试,用于改造 2 请求的自定义调用类:响应具有私有访问权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我创建自定义 Call 类时,我无法返回 Response,因为 Response 类是最终的.有什么解决方法吗?

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();

我的 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
}

推荐答案

在更彻底地查看了 retrofit2 响应类之后,我发现有一个静态方法可以满足我的需求.所以,我只是改变了这一行:

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);

到:

return Response.success(placesResults);

现在一切正常.

这篇关于单元测试,用于改造 2 请求的自定义调用类:响应具有私有访问权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 07:53