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

JUnit测试中如何强制抛出异常以覆盖RuleScheduler的catch代码块

解决方案

你只需要利用Mockito的mock行为配置能力,让被mock的ExternalService调用executeRuleValidationForProposal方法时主动抛出异常即可覆盖catch分支。你之前将batchSize设为null也没触发异常,是因为Mockito对mock对象的方法默认执行空逻辑、返回默认值,不会主动抛出空指针等异常,必须主动配置抛出行为才会触发。

修改后的测试代码

import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class RuleSchedulerTest
{
    @Mock
    private ExternalService externalService;

    @InjectMocks
    // 原代码存在变量名和类名重名的问题,调整为小驼峰命名更规范
    private RuleScheduler ruleScheduler;

    @Before
    public void init()
    {
        ReflectionTestUtils.setField(ruleScheduler, "enabled", true);
        ReflectionTestUtils.setField(ruleScheduler, "batchSize", 5);
    }

    @Test
    public void testExecuteRuleValidationCatchBranch()
    {
        // 配置mock对象调用目标方法时主动抛出异常
        when(externalService.executeRuleValidationForProposal(anyInt()))
                .thenThrow(new RuntimeException("测试强制触发异常"));
        
        // 执行测试方法
        ruleScheduler.executeRuleValidation();
        
        // 可选:如果你的测试类中mock了log对象,可以添加下方验证逻辑,确认catch分支的日志代码确实被执行
        // verify(log, times(1)).error(anyString(), any(Exception.class));
    }
}

原理说明

executeRuleValidation方法的try块内唯一的外部依赖调用就是externalService.executeRuleValidationForProposal(batchSize),我们通过Mockito配置这个方法被调用时直接抛出RuntimeException,该异常会被后续捕获范围为Exception的catch块捕获,就能完整覆盖对应的catch分支代码。如果executeRuleValidationForProposal本身声明了受检异常,替换为对应受检异常抛出也可。

内容的提问来源于stack exchange,提问作者Deepjyoti De

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 06:18:04