title: Can I test HttpClient Request With MockRestServiceServer
body: <p>In my application, I have external third party API requests. I want to test my application with mocking this API requests.</p>
  
  <p>My Service Class:</p>
  
  <pre class="lang-java prettyprint-override"><code>String API_URL = "https://external.com/v1/%s";
  private CloseableHttpClient httpClient;
  public Result executeRequest(String apiVersion, String subUrl, HttpMethod httpMethod)
  {
      try
      {
          HttpRequestBase httpRequest;
          String url = String.format(API_URL, subUrl);
          if (httpMethod.equals(HttpMethod.GET))
          {
              httpRequest = new HttpGet(url);
          }
          else if (httpMethod.equals(HttpMethod.POST))
          {
              httpRequest = new HttpPost(url);
              ((HttpPost) httpRequest).setEntity(new StringEntity(requestBody, "UTF-8"));
          }
          ...
          headers.forEach(httpRequest::setHeader);
          HttpResponse response = httpClient.execute(httpRequest);
      }
      catch (IOException e)
      {
          logger.error("IO Error: {}", e.getMessage());
          return handleExceptions(e);
      }
  }
  </code></pre>
  
  <p>To sum up for service class, requests can be get, post, delete, put. And this requests will be processed with headers or body parts. Then will be handled as http request.</p>
  
  <p>My test class:</p>
  
  <pre class="lang-java prettyprint-override"><code>@SpringBootTest
  @ActiveProfiles("test")
  @RunWith(SpringRunner.class)
  public class ServiceTest
  {
  
      private static final String API_URL = "https://external.com/v1";
  
      @Autowired
      private Service service;
  
      @Autowired
      private RestTemplate restTemplate;
  
      private MockRestServiceServer mockServer;
  
       @Before
       public void init()
        {
          mockServer = MockRestServiceServer.createServer(restTemplate);
        }
  
      @Test
      public void getResult_successfully()
      {
          Result result = new Result();
          mockServer.expect(ExpectedCount.once(),
                  requestTo("/subUrl"))
                  .andExpect(method(HttpMethod.GET))
                  .andRespond(withStatus(HttpStatus.OK)
                          .contentType(MediaType.APPLICATION_JSON)
                          .body(gson.toJson(result))
                  );
  
          Result returnResult = service.executeRequest("/subUrl", GET);
  
          mockServer.verify();
          assertThat(returnResult).isEqualTo(result);
      }
  }
  </code></pre>
  
  <p>When I implement it like above, mocking doesn't work. Any suggestion?</p>
  
  <p>I know in here, MockRestServiceServer work only with restTemplate requests but I wonder there is a way to handle it with httpClient?</p>
  
  <p>Note: I hope code snippets will be enough to understand the code in overall. </p>