title: How to test restclient using RestTemplate and JUnit?
body: <p>I am new to JUNIT and using <code>RestTemplate</code> to call my service, I'm getting 200 response for the same. But, I can't test the class using JUnit. Tried different approaches and getting 400 and 404. I want to post the request body (json) and test the status. Please let me know if there is any issue.</p>
  <pre><code>/**
  * Rest client implementation
  **/  
  public class CreateEmailDelegate implements CDM {
           
      @Autowired
      private RestTemplate restTemplate;
      private  String url = &quot;http://example.com/communications/emails&quot;;
          
      public ResponseEntity&lt;CDResponse&gt; createEmail(CDMEmailRequest cDRequest) throws UnavailableServiceException, InvalidInputException {
          HttpHeaders httpHeaders = new HttpHeaders();
          httpHeaders.set(&quot;SR_API_Key&quot;, SR_API_KEY);
          httpHeaders.set(&quot;consumerIdentification&quot;, CONSUMER_IDENTIFICATION);
          httpHeaders.setContentType(MediaType.APPLICATION_JSON);         
          HttpEntity&lt; CDMEmailRequest &gt; cDRequestEntity = new HttpEntity&lt;&gt;( cDRequest, httpHeaders);  
          ResponseEntity&lt; CDResponse &gt; cDResponse = null;
                  
          try {
              cDResponse = restTemplate.postForEntity(url, cDRequestEntity, CDResponse.class);
          } catch (Exception e) {
              LOGGER.error(e.getMessage());
              throw  e;       
          }
                  
          return cDResponse;
      }
  }  
  </code></pre>
  <p>My Test class which return 404 status instead of 200</p>
  <pre><code>    @RunWith(SpringJUnit4ClassRunner.class)
      public class CreateEmailCommunicationDelegateTest {
      
          @Before
          public void setup() {
              httpHeaders = new HttpHeaders();
              httpHeaders.set(&quot;SR_API_Key&quot;, SR_API_KEY);
              httpHeaders.set(&quot;consumerIdentification&quot;, CONSUMER_IDENTIFICATION);
              httpHeaders.setContentType(MediaType.APPLICATION_JSON);
              DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(this.wac);
              this.mockMvc = builder.build();
          }
      
      
          public void testResponse() throws Exception, HttpClientErrorException, JsonProcessingException {
              String url = &quot;http://example.com/CommunicationDeliveryManagement-Service-1.0.0/communications/emails&quot;;
      
              CDMEmailRequest anObject = new CDMEmailRequest();
              ResultMatcher ok = MockMvcResultMatchers.status().isOk();
              ObjectMapper mapper = new ObjectMapper();
              mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
              ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
              String requestJson = ow.writeValueAsString(anObject);
      
              System.out.println(requestJson);
              MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.post(url).contentType(MediaType.APPLICATION_JSON_UTF8).content(requestJson);
              this.mockMvc.perform(builder).andExpect(ok).andDo(MockMvcResultHandlers.print());
          }
      } 
  
   
  </code></pre>
  <p>My Test class using <code>TestRestTemplate</code> instead <code>MockMvc</code> returns 400</p>
  <pre><code>@RunWith(SpringJUnit4ClassRunner.class)
  public class CreateEmailCommunicationDelegateTest {
  
      @Before
      public void setup() {
          httpHeaders = new HttpHeaders();
          // rest headers as above
      }
  
      @Test
      public void testResponse() throws Exception, HttpClientErrorException, JsonProcessingException {
  
          String url = &quot;http://example.com/CommunicationDeliveryManagement-Service-1.0.0/communications/emails&quot;;
  
          String username = &quot;&quot;;
          String password = &quot;&quot;;
          HttpEntity&lt;CDMEmailRequest&gt;
                  cDEntity = new HttpEntity&lt;&gt;(httpHeaders);
  
          restTemplate = new TestRestTemplate(username, password);
  
          responseEntity =
                  restTemplate.exchange(url, HttpMethod.POST, cDEntity,
                          CDResponse.class);
  
          assertNotNull(responseEntity);
          assertEquals(HttpStatus.OK,
                  responseEntity.getStatusCode());
      }
  } 
  </code></pre>