如何在Spring启动时模拟本地RestTemplate来解决连接被拒绝?

时间:2017-11-02 04:54:46

标签: java spring unit-testing mockito

这是我的代码。我想做的是测试三种异常。但我不知道如何模拟局部变量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这三种异常的方法吗?

1 个答案:

答案 0 :(得分:0)

首先不要在你的方法中实例化RestTemplate!让Spring为你创建它,例如将其添加到弹簧配置

@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
    return builder.build();
}

然后你就可以开始编写如下所述的休息客户端测试:

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features-testing-spring-boot-applications-testing-autoconfigured-rest-client