I want to mock a method which will call the external api in junit5 using mockito framework

53 Views Asked by At

I am not able to stub the response for restTemplate.exchange(apiurl,HttpMethod.get,httpEntity,new PrametrizedTypeReference<<>>){});

public static List<TapDetailPojo> getTapPostList(HttpServletRequest request,String apiUrl, String xApiKey,HttpServletResponse response) {
    //HttpSession session = request.getSession();
    //String idToken = (String) session.getAttribute("cognitoIdToken");
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.set("x-api-key",xApiKey);
    httpHeaders.setContentType(MediaType.APPLICATION_JSON);
    //httpHeaders.set("authorization", "Bearer " + idToken);
    List<TapDetailPojo> list = null;
    HttpEntity<String> httpEntity = new HttpEntity<String>(httpHeaders);
    try {
        ResponseEntity<List<TapDetailPojo>> entityResult = restTemplate.exchange(apiUrl, HttpMethod.GET, httpEntity,
                new ParameterizedTypeReference<List<TapDetailPojo>>() {
                });
     
      
        list = entityResult.getBody();
    
    }catch (HttpClientErrorException exe){
      printInputPojo(httpEntity, "Error", apiUrl);
    }catch(Exception e){
      printInputPojo(httpEntity, "Error", apiUrl);
      e.printStackTrace();
    }
    return list;
}

the above is my code

I want to stub the method when api is getting called but getting the value as null

1

There are 1 best solutions below

2
Devratna On

You can try following code

@Mock
private RestTemplate restTemplate;
@Test
void test_RestTempate() {

ResponseEntity<Class> dummyResponse = new ResponseEntity<>(MockResponse, HttpStatus.OK);

when(restTemplate.exchange(Mockito.anyString(), Mockito.eq(HttpMethod.POST), Mockito.any(HttpEntity.class), Mockito.<Class<?>>any()).thenReturn(dummyResponse);
}