这是我的代码。我想做的是测试三种异常。但是我不知道如何模拟局部变量 restTemplate。
我的代码:
private void setJobInstanceInfo(JobInstance jobInstance, String uri, String group, String jobName) {
RestTemplate restTemplate = new RestTemplate();
TypeReference<HashMap<String, Object>> type = new TypeReference<HashMap<String, Object>>() {
};
try {
String resultStr = restTemplate.getForObject(uri, String.class);
HashMap<String, Object> resultMap = JsonUtil.toEntity(resultStr, type);
setJobInstanceIdAndUri(jobInstance, resultMap);
} catch (RestClientException e) {
LOGGER.error("spark session {} has overdue, set state as unknown!n {}", jobInstance.getSessionId(), e.getMessage());
setJobInstanceUnknownStatus(jobInstance);
} catch (IOException e) {
LOGGER.error("jobInstance jsonStr convert to map failed. {}", e.getMessage());
} catch (IllegalArgumentException e) {
LOGGER.warn("Livy status is illegal. {}", group, jobName, e.getMessage());
}
}
当调用restTemplate.getForObject(uri, String.class)
时,它总是抛出异常,如下所示:
"I/O error on GET request for url: Connection refused: connect".
我知道这是网址问题。这就是我想嘲笑并返回我所期望的任何东西。那么,你能给出方法来测试RestClientException和IOException和IllegalArgumentException的这三种异常吗?
首先不要在你的方法中实例化 RestTemplate!让 Spring 为您创建它,例如将其添加到弹簧配置中
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
然后,您可以开始编写 rest 客户端测试,如下所述:
https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features-testing-spring-boot-applications-testing-autoconfigured-rest-client