title: How to Mock rest service
body: <p>I'm wondering how do I mock the rest controller for the code below,</p>
  
  <pre><code>public void sendData(ID id, String xmlString, Records record) throws  ValidationException{
          ClientHttpRequestFactory requestFactory = new
                  HttpComponentsClientHttpRequestFactory(HttpClients.createDefault());
          RestTemplate restTemplate = new RestTemplate(requestFactory);
  
          List&lt;HttpMessageConverter&lt;?&gt;&gt; messageConverters = new ArrayList&lt;&gt;();
          messageConverters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
  
          restTemplate.setMessageConverters(messageConverters);
  
          MultiValueMap&lt;String,String&gt; header = new LinkedMultiValueMap&lt;&gt;();
          header.add("x-api-key",api_key);
          header.add("Content-Type",content_type);
          header.add("Cache-Control",cache_control);
          HttpEntity&lt;String&gt; request = new HttpEntity&lt;&gt;(xmlString, header);
  
          try {
              restTemplate.postForEntity(getUri(id,record), request, String.class);
          }catch (RestClientResponseException e){
              throw new ValidationException("Error occurred while sending a file to some server "+e.getResponseBodyAsString());
          }
  
      }
  </code></pre>
  
  <p>Any suggestion would be helpful.
  I tried to do something like this,</p>
  
  <pre><code>  @RunWith(MockitoJUnitRunner.class)
      public class Safe2RestControllerTest {
          private MockRestServiceServer server;
          private RestTemplate restTemplate;
          private restControllerClass serviceToTest;
  
       @Before
       public void init(){
      //some code for initialization of the parameters used in controller class
          this.server = MockRestServiceServer.bindTo(this.restTemplate).ignoreExpectOrder(true).build();
       }
  
        @Test
          public void testSendDataToSafe2() throws ValidationException, URISyntaxException {
  
          //some code here when().then()
          String responseBody = "{\n" +
                      "    \"responseMessage\": \"Validation succeeded, message 
                           accepted.\",\n" +
                      "    \"responseCode\": \"SUCCESS\",\n" +
                      "    2\"responseID\": \"627ccf4dcc1a413588e5e2bae7f47e9c::0d86869e-663a-41f0-9f4c-4c7e0b278905\"\n" +
                      "}";
          this.server.expect(MockRestRequestMatchers.requestTo(uri))
        .andRespond(MockRestResponseCreators.withSuccess(responseBody, 
         MediaType.APPLICATION_JSON));
  
          serviceToTest.sendDataToSafe2(id, xmlString, record);
          this.server.verify();
          }
      }
  </code></pre>
  
  <p>This is the test case what I'm trying to do but it still calling actual rest api </p>