title: How to mock RestTemplate exchange?
body: <p>I want to unit test assignApplicationsToUser. A list of applicationId and user id is given and I have a URL to validate a user. I am getting an exception mentioned below.</p>
  <pre><code>java.lang.NullPointerException: Cannot invoke &quot;com.fasterxml.jackson.databind.JsonNode.asText()&quot; because the return value of &quot;com.fasterxml.jackson.databind.JsonNode.get(String)&quot; is null
  </code></pre>
  <p>AssignmentService.java</p>
  <pre><code>public class AssignmentService implements AssignemetServiceInterface {
      @Autowired
      AppInterceptor appInterceptor;
      @Autowired
      AssignmentRepository assignmentRepository;
      @Autowired
      private RestTemplate restTemplate;
      private String uri=&quot;http://localhost:8080/api/users/&quot;+uuid;
  
      @Override
      public List&lt;String&gt; assignApplicationsToUser(List&lt;String&gt; applications, String uuid)
              throws SQLException, RequestEntityNotFoundException {
  
          HttpHeaders headers = new HttpHeaders();
          headers.set(&quot;token&quot;, appInterceptor.getLoggedInUser());
          HttpEntity&lt;String&gt; requestEntity = new HttpEntity&lt;&gt;(null, headers);
          String result = restTemplate.exchange(uri, HttpMethod.GET, requestEntity, String.class).getBody();
  
          ObjectMapper objectMapper = new ObjectMapper();
          List&lt;String&gt; response = new ArrayList&lt;&gt;();
          JsonNode responseJson = objectMapper.readTree(result);
          if (responseJson.get(&quot;data&quot;) == null
                      &amp;&amp; responseJson.get(&quot;error&quot;).get(&quot;status&quot;).asText().equals(&quot;NOT_FOUND&quot;)) {
                  throw new RequestEntityNotFoundException(uuid, &quot;find&quot;);
          }
  
          for (String application : applications) {
          ApplicationAssignment isAssigned = assignmentRepository.findOneByApplicationId(application);
              if (isAssigned != null) {
                  isAssigned.setIsUser(true);
                  response.add(application + &quot; reassigned to &quot;+ uuid);
                  isAssigned.setAssignedTo(uuid);
                  this.assignmentRepository.save(isAssigned);
                  } 
             else {
            ApplicationAssignment newApplication = new ApplicationAssignment(application, uuid, true);
      
              this.assignmentRepository.save(newApplication);
              response.add(application + &quot; assigned successfully&quot;);
          }
         }
      return response;
  }
  }
  </code></pre>
  <p>sample input:
  {
  applications :[&quot;APP001&quot;,&quot;APP002&quot;,&quot;APP003&quot;,&quot;APP004&quot;],
  uuid : &quot;user1&quot;
  }</p>
  <p><strong>Edited :</strong>
  I have added sample response for the same.</p>
  <pre><code>{
      &quot;data&quot;: {
          &quot;id&quot;: &quot;fa727274-5a74-428a-b0f6-501eebafd8e8&quot;,
          &quot;name&quot;: &quot;Akash&quot;,
          &quot;email&quot;: &quot;AkashTyagi@fico.com&quot;,
          &quot;phone&quot;: 8799190991,
          &quot;isActive&quot;: true,
          &quot;createdBy&quot;: &quot;abhishekjaiswal@fico.com&quot;,
          &quot;updatedBy&quot;: null,
          &quot;creationTimeStamp&quot;: &quot;2021-08-11T11:23:05.356+00:00&quot;,
          &quot;updationTimeStamp&quot;: null
      },
      &quot;error&quot;: null,
      &quot;timeStamp&quot;: &quot;2021-08-16T05:02:04.866+00:00&quot;,
      &quot;success&quot;: true
  }
  </code></pre>
  <p>AssignmentServiceTest.java</p>
  <pre><code>@RunWith(MockitoJUnitRunner.class)
  @SpringBootTest
  public class AssignmentServiceTest {
  
      private static final Logger LOGGER = LoggerFactory.getLogger(AssignmentServiceTest.class);
      @InjectMocks
      private AssignmentService assignmentService;
      
      @Mock
      private AssignmentRepository assignmentRepo;
      
      @Mock
      private AppInterceptor appInterceptor;
      
      @Mock
      private RestTemplate restTemplate;
      
      ObjectMapper  objectMapper;
      String jsonString=&quot;{\r\n&quot;
              + &quot;    \&quot;data\&quot;: {\r\n&quot;
              + &quot;        \&quot;id\&quot;: \&quot;fa727274-5a74-428a-b0f6-501eebafd8e8\&quot;,\r\n&quot;
              + &quot;        \&quot;name\&quot;: \&quot;Akash\&quot;,\r\n&quot;
              + &quot;        \&quot;email\&quot;: \&quot;AkashTyagi@fico.com\&quot;,\r\n&quot;
              + &quot;        \&quot;phone\&quot;: 8799190991,\r\n&quot;
              + &quot;        \&quot;isActive\&quot;: true,\r\n&quot;
              + &quot;        \&quot;createdBy\&quot;: \&quot;abhishekjaiswal@fico.com\&quot;,\r\n&quot;
              + &quot;        \&quot;updatedBy\&quot;: null,\r\n&quot;
              + &quot;        \&quot;creationTimeStamp\&quot;: \&quot;2021-08-11T11:23:05.356+00:00\&quot;,\r\n&quot;
              + &quot;        \&quot;updationTimeStamp\&quot;: null\r\n&quot;
              + &quot;    },\r\n&quot;
              + &quot;    \&quot;error\&quot;: null,\r\n&quot;
              + &quot;    \&quot;timeStamp\&quot;: \&quot;2021-08-16T05:02:04.866+00:00\&quot;,\r\n&quot;
              + &quot;    \&quot;success\&quot;: true\r\n&quot;
              + &quot;}&quot;;;
              
      JsonNode mock;
      
      @BeforeEach
      private void setUp() throws JsonMappingException, JsonProcessingException {
      
           objectMapper = new ObjectMapper();
           mock = org.mockito.Mockito.mock(JsonNode.class);
      }
      @Test
      public void test_assignApplicationsToUser() throws NullPointerException, SQLException, RequestEntityNotFoundException, IndexOutOfBoundsException,JsonProcessingException, URISyntaxException{
  
          LOGGER.info(&quot;Begin of test_assignApplicationToUser method&quot;);
  
          
          ApplicationAssignment applicationAssignment = new ApplicationAssignment(&quot;1&quot;,&quot;u1&quot;,true);
          ApplicationAssignment savedApplicationAssignment = new ApplicationAssignment(&quot;1&quot;,&quot;u2&quot;,true);
      
  
          ResponseEntity&lt;String&gt; myEntity = new ResponseEntity&lt;String&gt;(&quot;{\r\&quot;error\&quot;:null\r}&quot;,HttpStatus.ACCEPTED);
          
          
          Mockito.when(restTemplate.exchange(
                  ArgumentMatchers.anyString(),
                  ArgumentMatchers.any(HttpMethod.class),
                  ArgumentMatchers.any(),
                  ArgumentMatchers.&lt;Class&lt;String&gt;&gt;any())).thenReturn(myEntity);
          
          Mockito.when(appInterceptor.getLoggedInUser()).thenReturn(&quot;abhishek@fico.com&quot;);
  
       
          Mockito.when(mock.get(&quot;data&quot;)).thenReturn(mock);
          Mockito.when(mock.get(&quot;error&quot;)).thenReturn(mock);
          Mockito.when(mock.get(&quot;error&quot;).asText()).thenReturn(&quot;FOUND&quot;);
          LOGGER.info(&quot;Node value &quot;+ mock.asText());
          
          Mockito.when(assignmentRepo.findOneByApplicationId(&quot;1&quot;)).thenReturn(applicationAssignment);
          Mockito.when(assignmentRepo.save(ArgumentMatchers.any())).thenReturn(savedApplicationAssignment);
   
          // Mock the input List of applications
          List&lt;String&gt; listOfApplication = new ArrayList&lt;&gt;();
          listOfApplication.add(&quot;app1&quot;);
          listOfApplication.add(&quot;app2&quot;);
          List&lt;String&gt; response = assignmentService.assignApplicationsToUser(listOfApplication,&quot;u1&quot;);
          assertEquals(response.get(0),&quot;app1 assigned successfully&quot;);
      }
  }
  
  </code></pre>