title: How to write unit test with okhttp using Mockito & Spring Boot
body: <p>I am trying to use okhttp with Mockito in my spring boot application but I am always getting NullPointerException at line</p>
  <p>httpClient.newCall(request).execute()</p>
  <p>How do we use Mockito with okhttp?</p>
  <pre><code>@Component
  public class HStatus {
  
      @Autowired
      private OkHttpClient httpClient;
  
      public int HCheck() throws URISyntaxException, IOException {
  
          String url = new URIBuilder(&quot;Some URL&quot;).build().toString();
  
          Request request = new Request.Builder().url(url).get().build();
  
          try (Response resp = httpClient.newCall(request).execute()) {
  
              return resp.code();
  
          }
  
      }
  </code></pre>
  <p>In junit, I am trying to do -</p>
  <pre><code>
  @RunWith(MockitoJUnitRunner.class)
  public class HStatusTest {
      
      @InjectMocks
      private HStatus hStatus;
  
      @Mock
      private OkHttpClient httpClient;
  
  
      @Test
      public void TestHCheck_Should_Return_200_StatusCode() throws URISyntaxException, IOException {
  
          Response resp = new Response.Builder()
                  .request(new Request.Builder().url(&quot;SOME URL&quot;).build())
                  .protocol(Protocol.HTTP_1_1)
                  .code(200).message(&quot;&quot;)
                  .build();
  
          Mockito.when(httpClient.newCall(ArgumentMatchers.any()).execute).thenReturn(resp);
  
  // Getting NullPointer at this call -&gt; httpClient.newCall(ArgumentMatchers.any()).execute
  
          int statusCode = hStatus.HCheck();
          
          assertEquals(200, statusCode);
  
      }
  }
  </code></pre>