Deepjyoti De
Deepjyoti De

Reputation: 127

Throw exceptions forcefully in JUnit Testing

I was going to increase the code coverage. In the process, I was unable to test the catch block of a specific method. I was trying to force exceptions to the method call.

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);
            }

        }
    }
}

I was trying different ways to throw exceptions to get into the catch block of the above code, but was unable to do so. And here is my Test class. Even the batchsize is accepting null values.

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();
    }

}

Upvotes: 0

Views: 2731

Answers (1)

j_b
j_b

Reputation: 2020

One possibility would be to configure your mock externalService instance to throw an exception. You should be able to then verify the interaction with the mock. Something like the following:

@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));

    }

Upvotes: 1

Related Questions