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

Mockito单元测试中如何验证RestClientException异常?

验证RestClientException异常的测试方案

你当前的测试代码无法触发RestClientException,原因是你让RestTemplate返回了HttpStatus.SERVICE_UNAVAILABLE的响应实体,但这种场景下RestTemplate不会抛出异常,只会正常返回响应,被测试类只会进入else分支打印错误日志,不会触发catch块的异常逻辑。

要验证RestClientException,需要让RestTemplate在调用exchange方法时直接抛出该异常,修改后的测试代码如下:

@Test
void test_update_customer_in_ath0_server_error() {
    // given
    doThrow(new RestClientException("模拟服务调用异常"))
            .when(restTemplate).exchange(any(), eq(HttpMethod.PATCH), any(HttpEntity.class), (Class<String>)any());

    // then - 验证方法抛出指定异常
    Assertions.assertThrows(RestClientException.class, () -> {
        idpFacadeClient.updateCustomerFirstNameInIdp(updateRecordsDto);
    });
    
    // 验证RestTemplate的exchange方法被正确调用
    verify(restTemplate).exchange(any(), eq(HttpMethod.PATCH), argThat(this::verifyUpdatedCustomerBody), (Class<String>)any());
}

关键修改说明

  • 用doThrow替代doReturn,让RestTemplate调用exchange时直接抛出RestClientException
  • 通过Assertions.assertThrows验证被测试方法确实会抛出目标异常
  • 保留原有的verify逻辑,确保调用exchange时使用了正确的参数

原测试类代码

@Test
void test_update_customer_in_ath0_server_error(){
    //given
    ResponseEntity<String> responseEntity = new ResponseEntity<>(HttpStatus.SERVICE_UNAVAILABLE);
    doReturn(responseEntity)
            .when(restTemplate).exchange(any(), eq(HttpMethod.PATCH), any(HttpEntity.class), (Class<String>)any());

    idpFacadeClient.updateCustomerFirstNameInIdp(updateRecordsDto);

    //then
    verify(restTemplate).exchange(any(), eq(HttpMethod.PATCH), argThat(this::verifyUpdatedCustomerBody), (Class<String>)any());
}

被Mock类代码

try {
    response = restTemplate.exchange(URI.create(idpFacadeUpdateUrl), HttpMethod.PATCH, entity,  String.class);
    if (response.getStatusCode() == HttpStatus.OK) {
        log.info("customer first name update success {} with status {}", customerUpdateRecordsDto.getFirstName(), response.getStatusCode());
    }else {
        log.error("Customer first name update failed in IDP for {} with status {}", customerUpdateRecordsDto.getFirstName(), response.getStatusCode());
    }
} catch (RestClientException e) {
    throw new RestClientException("Idp facade API error for user first name " + customerUpdateRecordsDto.getFirstName(), e);
}

内容的提问来源于stack exchange,提问作者clement mensah

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 03:15:48