Testing real network responses with modification

Before I get the mandatory โ€œyou should not test real network responses for XYZ reasons!โ€, It should be noted that I am not asking if I need to do this.

I specifically ask how I would do this if I wanted to.

After several hours of struggle, I successfully managed the correct answer from Volley and passed this test.

The problem I am facing right now is that call.enque(...)it seems to hang on the RobolectricTestRunner. Unlike Volley, I can't look and see what happens there (for Volley, the problem was not that Looper.getMainLooper was not created properly.)

So all I do is make a simple server request using Retrofit. The problem, as I said, is that the whole system hangs at call.enqueue, and there is no error or answer ever (even when my wait is longer). A network call works great with volleyball, but I get this snag here with Retrofit. Here is the code if you want to try it. And, of course, the function works fine when the application is running.

    //in NetworkManager.class
    public void someCall(HashMap properties, NetworkResponseListener listener){
        this.okHttpClient = new OkHttpClient.Builder().cache(new Cache(appContext, 35 * 1024 * 1024)).build();
        this.retrofit = new Retrofit.Builder().baseUrl(httpPath + apiHost).client(okHttpClient).build();
        this.myService = retrofit.create(MyService.class);

        Call call = myService.someRequest(properties);

        call.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
                        listener.onSuccess(response);
                    }
                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        listener.onError(t);
                    }
                });
    }

Services:

interface MyService {
    @GET("/api/SomeEndpoint/")
    Call<ResponseBody> someRequest(@QueryMap Map<String, Object> params);
}

Test:

@Test
public void testSomeCall() throws Exception {
    //Network class has setup OkHttpClient/Service/Retrofit already
    NetworkResponseListener listener = new NetworkResponseListener() {
        @Override
        public void onSuccess(Response response) {
            this.response = response;
        }

        @Override
        public void onError(Throwable error) {
          //
        }
    };

    NetworkManager.someCall(this.properties, listener);

    await().atMost(30, TimeUnit.SECONDS).until(ResponseReceived());
}

Each answer to stackoverflow was โ€œnot testing real network responsesโ€, which really doesn't help.

+4
source share
1 answer

The solution is pretty much like for volleyball .

Retrofit2 , .

. , callbackExector. :

retrofit = new Retrofit.Builder().baseUrl(baseUrl)
     .client(okHttpClient).callbackExecutor(Executors.newSingleThreadExecutor())

.

+1

All Articles