You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Retry单元测试抛出Checked异常无效问题求助

问题排查与解决

错误根源

RestTemplate的getForEntity()方法仅抛出非受检异常(RuntimeException子类),比如RestClientException、HttpClientErrorException等,它的方法签名里并未声明抛出受检的Exception类。当你用Mockito模拟抛出Exception.class时,Mockito会校验目标方法是否允许抛出该异常——受检异常不符合方法签名要求,因此触发Checked exception is invalid for this method!错误。

解决步骤

  1. 替换抛出的异常类型:把测试代码中抛出的Exception.class换成RestTemplate实际会抛出的RuntimeException子类,比如RestClientException或更具体的异常(如请求超时的ResourceAccessException、4xx错误的HttpClientErrorException)。

    错误示例:

    when(restTemplate.getForEntity(anyString(), eq(Product.class)))
        .thenThrow(Exception.class); // 抛出受检异常,不符合方法签名
    

    正确示例:

    when(restTemplate.getForEntity(anyString(), eq(Product.class)))
        .thenThrow(RestClientException.class); // 用非受检异常模拟
    
  2. 验证捕获逻辑:业务代码中的catch(Exception e)块会自动捕获所有RuntimeException(因为RuntimeException是Exception的子类),修改后测试就能正常触发catch块,完成代码覆盖。

  3. 可选:模拟真实场景:如果需要复现特定HTTP错误,可使用更具体的异常类:

    when(restTemplate.getForEntity(anyString(), eq(Product.class)))
        .thenThrow(new HttpClientErrorException(HttpStatus.NOT_FOUND));
    

内容的提问来源于stack exchange,提问作者Sweta Sharma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 01:43:13