title: Mocking okhttp response
body: <p>I have the below method  which executes a GET request 3 times until its successfully.</p>
  
  <p>What would be the better way to mock this method? I want to mock and test status_code 401, status code 500 and want to test if the method is executed thrice.</p>
  
  <p>In python, we have <a href="https://github.com/getsentry/responses" rel="noreferrer">https://github.com/getsentry/responses</a> which mocks the requests directly, so its easy to test these methods.</p>
  
  <p>Is there anything equivalent in Java.</p>
  
  <pre><code>@Override
      public &lt;T&gt; UResponse&lt;T&gt; get(Request request, JSONUnmarshaler&lt;T&gt; unmarshaller, Gson gson) throws UException {
          int status_code = 0;
          String next = null;
          String rawJSON = null;
          JsonElement jsonelement = null;
          Boolean retry = true;
          try {
              int attempts = 3;
              while ((attempts &gt;= 0)  &amp;&amp; (retry) &amp;&amp; status_code != 200){
                  Response response = this.client.newCall(request).execute();
  
                  rawJSON = response.body().string();
  
                  jsonelement = gson.fromJson(rawJSON, JsonElement.class);
  
                  next = gson.fromJson(jsonelement.getAsJsonObject().get("next"), String.class);
  
                  status_code = response.code();
  
                  if (status_code == 401) {
                      try {
                          logger.warn("token expired");
                          TimeUnit.SECONDS.sleep(5);
                          retry = true;
                      } catch (InterruptedException e) {
                          e.printStackTrace();
                      }
                  }
  
                  if ((status_code / 100 ) == 5){
                      logger.warn("gateway error");
                      retry = true;                   
                  }
                  attempts -= 1;
                  retry = false;
  
              }
              if (status_code != 200){
                  throw new UException();
              }
              return new UResponse&lt;T&gt;(status_code, next, rawJSON,
                      unmarshaller.fromJSON(gson, jsonelement.getAsJsonObject()));
  
          } catch (IOException e) {
              e.printStackTrace();
              throw new UException();
  
          }
  </code></pre>