模拟 resttemplate getbody 返回空指针异常



我有一个使用 resttemplate 调用休息服务的类。

Class MyService{
  RestTemplate resttemplate = new RestTemplate();
 public void handler(){
   string token;
    token = restTemplate.exchange(authurl, HttpMethod.POST, getHttpEntity(tenantLogin, basicAuth), String.class)
          .getBody();
}
 private static <T> HttpEntity<T> getHttpEntity(T jsonRequest, String authorization) {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.set("Authorization", authorization);
    return new HttpEntity<T>(jsonRequest, headers);
  }
}

对于上面,我的测试类如下。

Class restTemplateTest{
 RestTemplate restTemplate = mock(RestTemplate.class);
  Field fieldReflectionUtil = 
  ReflectionUtils.findField(Myservice.class, "restTemplate");
    ReflectionUtils.makeAccessible(fieldReflectionUtil);
    ReflectionUtils.setField(fieldReflectionUtil, handler, restTemplate);
    HttpHeaders headers = new HttpHeaders();
    headers.set("Content-Type", "application/json");
    List<String> payload = new ArrayList<>();
  when(restTemplate.exchange(Mockito.anyString(), Mockito.<HttpMethod> eq(HttpMethod.POST),
        Mockito.eq(new HttpEntity<>(payload.toString(), headers)), Mockito.<Class<Object>> any()).getBody())
            .thenReturn(Mockito.anyString());

}

restemplate getbody(( 给出 nullpointer 异常。

嘲笑 resttemplate 的方式有问题吗?

谢谢安贾娜。

你应该返回一些虚拟字符串或 json 字符串。

String token="$11234qwer";
 when(restTemplate.exchange(Mockito.anyString(), Mockito.<HttpMethod> 
 eq(HttpMethod.POST),
 Mockito.eq(new HttpEntity<>(payload.toString(), headers)), Mockito.<Class<Object>> 
 any()).getBody()).thenReturn(token);

相关内容

  • 没有找到相关文章

最新更新