我有一个使用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()正在给出nullpointer异常。
模仿resttemplate的方式是否有问题。
谢谢, 美国之音。
答案 0 :(得分:0)
您应该返回一些虚拟字符串或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);