title: Testing okHttp requests with Robolectric - callbacks
body: <p>I have a function that I want to test which runs in an okHttp callback. I'm trying to test it using Robolectrics but the callback is never executed. I presume that is because the test moves on after request without waiting for okHttp to return. So far I've tried:</p>
  
  <pre><code>    ShadowLooper.pauseMainLooper();
      Robolectric.flushBackgroundScheduler();
      ShadowLooper.unPauseMainLooper();
  </code></pre>
  
  <p>but that didn't work. Any suggestions?</p>
  
  <p>EDIT:</p>
  
  <p>Here's an example of my code:</p>
  
  <pre><code>ApiClient.sendSomeDataToServer(data, callback);
  </code></pre>
  
  <p>Where ApiClient is a helper class containing okHttp client. sendSomeDataToServer API call looks something like this:</p>
  
  <pre><code>public static void sendSomeDataToServer(MyObject data, Callback callback){
      final Request request = new Request.Builder()
              .url(API_SOME_URL)
              .post(RequestBody.create(JSON, myObject.getAsJson().toString()))
              .build();
      sHttpClient.newCall(request).enqueue(callback);
  }
  </code></pre>
  
  <p>Where sHttpClient is an initialised OkHttpClient.</p>
  
  <p>I can test the execution of above by forcing <code>Thread.sleep(5000)</code> inside my test code and providing custom callback. The code I'm trying to test is inside the callback. Any suggestions how I can test that? I really don't want to change the main code to fit the test framework - should be the other way round.</p>