首页 > 解决方案 > 在 JUnit 测试中强行抛出异常

问题描述

我打算增加代码覆盖率。在此过程中,我无法测试特定方法的 catch 块。我试图强制方法调用出现异常。

RuleSchedule.java

public class RuleScheduler
{

    private boolean                 enabled;

    private Integer                 batchSize;

    @Autowired
    private ExternalService externalService;


    public void executeRuleValidation()
    {
        if (enabled)
        {
            try
            {
                StopWatch stopWatch = new StopWatch();
                stopWatch.start();
                externalService.executeRuleValidationForProposal(batchSize);
                stopWatch.stop();
                log.info("Total time taken for RuleValidation:{} for batchSize :{}",
                    stopWatch.getTotalTimeSeconds(), batchSize);
            }
            catch (Exception ex)
            {
                // System.out.println("~~~~~~CATCH~~~~~~");
                log.error("Rule exception :{}", ex);
            }

        }
    }
}

我正在尝试不同的方法来引发异常以进入上述代码的 catch 块,但无法这样做。这是我的测试课。甚至批量大小也接受空值。

RuleScheduleTest.java

@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 testExecuteRuleValidation()
    {
        RuleScheduler.executeRuleValidation();
    }

}

标签: javaunit-testingjunitmockitocode-coverage

解决方案


一种可能性是配置您的模拟externalService实例以引发异常。然后,您应该能够验证与模拟的交互。类似于以下内容:

@Test
public void testExecuteRuleValidation(){
       // configure your mock 'externalService' instance to throw an exception
       when(externalService.executeRuleValidationForProposal(any(Integer.class))).thenThrow(IllegalArgumentException.class);

       RuleScheduler.executeRuleValidation();

       // now verify mock interaction
       verify(externalService, times(1)).executeRuleValidationForProposal(any(Integer.class));

    }

推荐阅读