title: How to use Mockito to mock a request in Jersey client?
body: <p>I have a class to post POJO to an external API. I want to test this method.</p>
  
  <pre><code>public int sendRequest(Event event) {
  
     Client client = ClientBuilder.newClient();
     WebTarget baseTarget = client.target(some url);
     Invocation.Builder builder = baseTarget.request();
     Response response = builder.post(Entity.entity(event, MediaType.APPLICATION_JSON));
     int statusCode = response.getStatus();
     String type = response.getHeaderString("Content-Type");
  
  
    if (Status.Family.SUCCESSFUL == Status.Family.familyOf(statusCode)) {
          m_log.debug("The event was successfully processed by t API %s", event);
    }
  
    else if (Status.Family.CLIENT_ERROR == Status.Family.familyOf(statusCode)) {
        m_log.error("Status code : &lt;%s&gt; The request was not successfully processed by API. %s", statusCode, event);
    }
  
    return statusCode;
   }
  </code></pre>
  
  <p>I wrote a unit test like this </p>
  
  <pre><code>@Test
    public void sendRequest_postAuditEvent_returnOK() {
    int statusCode = EventProcessor.sendRequest(event);
    assertEquals(Status.OK.getStatusCode(), statusCode);
   }
  </code></pre>
  
  <p>But this will send a real request to the API. I am new to Mockito. Can anyone help me how to mock this request?</p>
  
  <p>Edit:</p>
  
  <pre><code>@Mock Client m_client;
  @Mock WebTarget m_webTarget;
  @Mock Invocation.Builder m_builder;
  @Mock Response m_response;
  
  @Test
  public void sendRequest_postAuditEvent_returnOK() {
    when(m_client.target(anyString())).thenReturn(m_webTarget);
    when(m_webTarget.request()).thenReturn(m_builder);
    when(m_builder.post(Entity.entity(m_AuditEvent, MediaType.APPLICATION_JSON))).thenReturn(m_response);
    when(m_response.getStatus()).thenReturn(Response.Status.BAD_REQUEST.getStatusCode());
    assertEquals(Status.BAD_REQUEST.getStatusCode(), m_AuditEventProcessor.sendRequest(m_AuditEvent));
  }
  </code></pre>
  
  <p>I try to mock the methods but it doesn't work. Still call the real method.</p>