Java 如何对HttpClientErrorException和HttpServerErrorException块进行代码覆盖

Java 如何对HttpClientErrorException和HttpServerErrorException块进行代码覆盖,java,mockito,Java,Mockito,我试图在下面介绍HttpClientErrorException、HttpServerErrorException块,但下面的代码无法涵盖。有人能帮我解决我的问题吗 等级 public void refreshCall(RefreshCartRequest请求,列出错误){ 字符串url=Utils.formatHttpUrl(url,刷新url); 试一试{ HttpEntity=新的HttpEntity(请求); JsonNode JsonNode=restTemplate.postForO

我试图在下面介绍HttpClientErrorException、HttpServerErrorException块,但下面的代码无法涵盖。有人能帮我解决我的问题吗

等级
public void refreshCall(RefreshCartRequest请求,列出错误){
字符串url=Utils.formatHttpUrl(url,刷新url);
试一试{
HttpEntity=新的HttpEntity(请求);
JsonNode JsonNode=restTemplate.postForObject(url、实体、JsonNode.class);
}捕获(HttpClientErrorE异常){
errors.add(ErrorMessages.SM_ERR_05);
返回;
}捕获(HttpServerErrorException){
errors.add(ErrorMessages.SM\u ERR\u 03);
返回;
}
}
测试班
@Test(预期=ServiceException.class)
公共无效测试\u刷新调用\u服务器异常(){
RefreshCartRequest req=新的RefreshCartRequest();
HttpEntity=新的HttpEntity(req);
当(restTemplate.postForObject(URL,entity,JsonNode.class)).ThentThrow(HttpServerErrorException.class);
refreshCall(req,newarraylist());
}

在测试方法中传入的实体与为其设置thenThrow的实体不同(在方法中调用
new
)。更改为使用
Matchers.eq
Matchers.any
when
设置中根据需要,否则调用将不匹配。@BeUndead能否请您建议使用code我手边没有IDE,因此无法轻松检查。但是类似于
doThrow(new-HttpClientErrorException()).when(restemplate).postForObject(Matchers.any(URL.class)、Matchers.any(HttpEntity.class)、Matchers.any(class.class))问题在于您设置它的方式,只有提供了这些确切的参数,它才会抛出,但在方法中,它是HttpEntity的另一个实例。
public void refreshCall(RefreshCartRequest request, List<ResolvableErrorEnum> errors) {
        String url = Utils.formatHttpUrl(url, REFRESH_URL);
        try {
            HttpEntity<?> entity = new HttpEntity<>(request);
            JsonNode jsonNode = restTemplate.postForObject(url, entity, JsonNode.class);
        } catch (HttpClientErrorException e) {
            errors.add(ErrorMessages.SM_ERR_05);
            return;
        } catch (HttpServerErrorException e) {
            errors.add(ErrorMessages.SM_ERR_03);
            return;
        }
    }
@Test(expected = ServiceException.class)
    public void test_refreshCall_ServerException() {
        RefreshCartRequest req = new RefreshCartRequest();
        HttpEntity<?> entity = new HttpEntity<>(req);    
when(restTemplate.postForObject(URL,entity,JsonNode.class)).thenThrow(HttpServerErrorException.class);
        client.refreshCall(req,new ArrayList<ResolvableErrorEnum>());
    }