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

JUnit最佳实践:是否需要测试运行时异常执行场景?

结论:该异常流的测试属于JUnit最佳实践
  • 你自定义的异常处理逻辑包含两个可验证的明确行为:打印带指定参数的错误日志、原样抛出DataAccessException不做额外包装。这两个都是你手动编写的业务逻辑,不属于框架默认实现,必须通过测试保证正确性。
  • 你的应用是Spring Boot Rest服务,上层通常配置了全局异常处理器,会把DataAccessException转换为对应的5xx服务错误响应返回给调用方。如果异常流逻辑出错(比如不小心删掉了throw e代码),会导致上层拿不到预期的异常,直接返回200或者其他不符合预期的响应,影响接口功能正确性。
  • 即使当前异常处理逻辑非常简单,测试也可以为后续迭代提供防护:比如后续有人修改日志格式、或者调整异常处理逻辑时,单元测试可以第一时间发现不符合预期的改动。
单测实现建议

不需要启动Spring上下文、也不需要连接真实数据库实现该测试,直接用单元测试+Mockito桩化依赖即可,执行效率高且无外部依赖。

@Test
void createReport_WhenDbAccessFails_ShouldLogErrorAndThrowOriginalException() {
    // 1. 准备测试数据
    String testReportType = "DAILY";
    Report testReport = new Report();
    testReport.setReportName("test_report_001");
    ReportUser testUser = new ReportUser();
    Timestamp testCreateTs = new Timestamp(System.currentTimeMillis());
    DataAccessException mockDbException = new DataAccessResourceFailureException("数据库连接断开");

    // 2. 桩化DAO方法,触发异常分支
    doThrow(mockDbException).when(reportDao)
        .saveReportDetails(eq(testReportType), eq(testReport), eq(testUser), eq(testCreateTs));

    // 3. 验证抛出的异常符合预期
    DataAccessException actualException = assertThrows(DataAccessException.class,
        () -> reportService.createReport(testReportType, testReport, testUser, testCreateTs));
    assertSame(mockDbException, actualException);

    // 4. 验证日志打印符合预期(可使用LogCaptor等工具实现)
    LogEvent errorLog = logCaptor.getErrorLogs().get(0);
    assertEquals("DataAccessException while trying to insert report with name test_report_001", 
        errorLog.getFormattedMessage());
    assertSame(mockDbException, errorLog.getThrowable());
}

内容的提问来源于stack exchange,提问作者Nestor Milyaev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 03:00:06