I finally figured it out. The idea is to use OkHttp application interceptors. Here is the solution.
First create a NetworkBehavior .
final NetworkBehavior behavior = NetworkBehavior.create(); behavior.setDelay(2000, TimeUnit.MILLISECONDS); behavior.setFailurePercent(50); behavior.setVariancePercent(50);
Of course, you can provide behavior the user interface component to dynamically change these values.
When configuring OkHttpClient add the following interceptor.
final OkHttpClient.Builder builder = new OkHttpClient.Builder(); if (!BuildConfig.IS_PRODUCTION_BUILD) { builder.addInterceptor(new HttpLoggingInterceptor()); builder.addInterceptor(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { try { Thread.sleep(behavior.calculateDelay(TimeUnit.MILLISECONDS)); } catch (InterruptedException e) { e.printStackTrace(); } if (behavior.calculateIsFailure()) { return new Response.Builder() .code(500) .message("MockError") .protocol(Protocol.HTTP_1_1) .request(chain.request()) .body(ResponseBody.create(MediaType.parse("text/plain"), "MockError")) .build(); } return chain.proceed(chain.request()); } }); }
Note that you must add a logging interceptor before sending request logs. Of course, a manually created response object can be adapted to your taste. Some values ββare required (e.g. protocol or request ). If you do not specify them, you will receive NPE. The same approach will indeed work for Retrofit 1.
Eugen source share