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.
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 {
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.