【问题标题】:Mock resttemplate getbody returns null pointer exception模拟resttemplate getbody返回空指针异常
【发布时间】:2018-03-16 08:58:36
【问题描述】:

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

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() 给出空指针异常。

resttemplate的mock方式是否有问题。

谢谢, 安佳娜。

【问题讨论】:

  • 你不能这样做.thenReturn(Mockito.anyString());你应该返回一些虚拟字符串
  • .thenReturn(Mockito.anyString()) 在 restTemplate.exchange(Mockito.anyString(), Mockito. eq(HttpMethod.POST) 上调用 getBody 时也返回空指针, Mockito.eq(new HttpEntity(payload.toString(), headers)), Mockito.> any())
  • 试试这个when(restTemplate.exchange(Mockito.anyString(), Mockito.&lt;HttpMethod&gt; eq(HttpMethod.POST), Mockito.eq(new HttpEntity&lt;&gt;(payload.toString(), headers)), Mockito.&lt;Class&lt;Object&gt;&gt; any()).getBody()) .thenReturn("dummyString");

标签: mockito resttemplate


【解决方案1】:

你应该返回一些虚拟字符串或 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多