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

Spring Boot中使用Mockito测试无返回值函数的try/catch代码块

用Mockito测试异常处理的实现思路与代码示例

没问题,我来帮你搞定用Mockito测试GettingMyDataService中try/catch异常逻辑的场景。核心思路就是mock掉MyCustomRestClient的callReadExternalSIService方法,让它抛出指定的HttpStatusException,然后验证你的服务类是否正确抛出对应的自定义异常。下面是具体的步骤和代码:

1. 测试类基础配置

首先,我们需要在测试类中使用Mockito的注解来创建mock对象并注入到待测试的服务中。确保你的测试类引入了必要的依赖:

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpStatus;
import org.springframework.web.client.HttpClientErrorException;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;

然后配置测试类:

@ExtendWith(MockitoExtension.class)
class GettingMyDataServiceTest {

    // 创建MyCustomRestClient的mock实例
    @Mock
    private MyCustomRestClient myCustomRestClient;

    // 将mock实例注入到待测试的GettingMyDataService中
    @InjectMocks
    private GettingMyDataService gettingMyDataService;
}

2. 测试404异常场景

当外部服务返回404时,我们需要验证服务类是否抛出CustomException1:

@Test
void whenExternalServiceReturns404_thenThrowCustomException1() {
    // 准备测试用的dataId
    String testDataId = "test-404-id";
    
    // 构造404异常(注意:Spring RestTemplate抛出的是HttpClientErrorException子类,可根据你的实际异常类型调整)
    HttpClientErrorException notFoundException = new HttpClientErrorException(HttpStatus.NOT_FOUND);

    // 配置mock行为:当调用callReadExternalSIService时抛出404异常
    when(myCustomRestClient.callReadExternalSIService(testDataId))
        .thenThrow(notFoundException);

    // 验证是否抛出预期的CustomException1
    CustomException1 actualException = assertThrows(CustomException1.class,
            () -> gettingMyDataService.getDataFunction(testDataId));
    
    // 可选:验证异常信息是否符合预期
    assertEquals(".......", actualException.getMessage());
    
    // 可选:确认mock方法确实被调用了一次
    verify(myCustomRestClient, times(1))
        .callReadExternalSIService(testDataId);
}

3. 测试非404的HTTP异常场景

当外部服务返回其他错误码(比如500、400)时,验证服务类是否抛出CustomException2:

@Test
void whenExternalServiceReturnsNon404Error_thenThrowCustomException2() {
    String testDataId = "test-500-id";
    
    // 构造500服务器错误异常
    HttpClientErrorException serverErrorException = new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR);

    // 配置mock行为
    when(myCustomRestClient.callReadExternalSIService(testDataId))
        .thenThrow(serverErrorException);

    // 验证异常类型和信息
    CustomException2 actualException = assertThrows(CustomException2.class,
            () -> gettingMyDataService.getDataFunction(testDataId));
    
    assertEquals(".....", actualException.getMessage());
    
    verify(myCustomRestClient, times(1))
        .callReadExternalSIService(testDataId);
}

几个关键注意点

  • 异常类型匹配:你代码中捕获的HttpStatusException,在Spring实际场景中通常是HttpStatusCodeException的子类(比如HttpClientErrorException、HttpServerErrorException),请确保测试中使用的异常类型和你的服务类捕获的一致,否则测试会失败。
  • 自定义异常的继承关系:如果CustomException1和CustomException2是继承自RuntimeException,那么assertThrows可以直接捕获;如果是受检异常,需要在测试方法上声明或者用try-catch处理。
  • mock的验证:使用verify方法可以确保外部服务的调用逻辑确实被触发,避免出现代码分支未覆盖的情况。

内容的提问来源于stack exchange,提问作者M. Dao

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 23:19:07