我想模拟一个方法,该方法将使用mockito框架调用junit5中的外部api

问题描述 投票:0回答:1

我无法存根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;
}

以上是我的代码

我想在调用 api 时存根该方法,但获取的值为 null

java spring-mvc mockito junit5 wiremock
1个回答
0
投票

您可以尝试以下代码

@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);
}
© www.soinside.com 2019 - 2024. All rights reserved.