title: How to mock a RestTemplate Exchange spring boot
body: <p>I have tried many ways to mock the restTemplate exchange, but the mock is not happening, the actual exchange keeps on calling and gives me url not valid exception.</p>
  <p>My CallRestService method is below</p>
  <pre class="lang-java prettyprint-override"><code>public class Util{
      
      public static ResponseEntity&lt;String&gt; callRestService(JSONObject reqJsonObj,HttpHeaders headers, String url, HttpMethod method, boolean isAuto){
          ResponseEntity&lt;String&gt; re=null;
          try{
              HttpEntity&lt;String&gt; entity=null;
              entity=new HttpEntity&lt;&gt;(String.valueOf(reqJsonObj),headers);
              RestTemplate restTemplate= new RestTemplate();
              re=restTemplate.exchange(url,method,entity,String.class);
          }catch(Exception e){
              System.out.println(e);
          }
      }
  }
  </code></pre>
  <p>And My Mock is below:</p>
  <pre class="lang-java prettyprint-override"><code>public class UtilTest{
      @InjectMocks
      Util util;
      @Mock
      RestTemplate restTemplate;
      ResponseEntity res=mock(ResponseEntity.class);
  
      @Test
      public void test(){
          //ResponseEntity&lt;String&gt; entity=new ResponseEntity&lt;String&gt;(&quot;anySt&quot;,HttpStatus.ACCEPTED);
          Mockito.when(restTemplate.exchange(
                  ArgumentMatchers.anyString(),
                  ArgumentMatchers.any(HttpMethod.class),
                  ArgumentMatchers.any(HttpEntity.class),
                  ArgumentMatchers.&lt;Class&lt;String&gt;&gt;any())
          ).thenReturn(res);
          Util.callRestService(json,headers,url,HttpMethod.POST,false);
      }
  }
  </code></pre>
  <p>I also tried to return the commented response Entity. but always got exception in exchange.</p>
  <p>What i understand about mocking is the actual exchange method will not be called, then how am i getting resttemplate exchange exception.</p>
  <p>if any inputs required pls comment.</p>
  <p>Thanks for the support.</p>
  <blockquote>
  <p>UPDATE:
  I tried with changing the static method to non static but kept the test case as is. But i get the same error</p>
  </blockquote>