Issue
Am writting Junit code coverage for the below java code and the code is not covering for Otherthan Runtime Exception
.
Please find my below java code.
public class NotifySupervisorJobTask implements Tasklet {
private static final Logger LOGGER = LoggerFactory.getLogger(NotifySupervisorJobTask.class);
@Autowired
private CoreClient client;
@Autowired
private ItemProcessFailedNotifier itemProcessFailedNotifier;
@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) {
try {
client.notifySupervisor(null);
LOGGER.info("notifySupervisorJobTask - execute() called");
} catch (RuntimeException exception) {
String errorMessage = format("Error in triggering notify supervisor job. Task will be repeated at next scheduled time. Error is: [%s]", exception.getMessage());
LOGGER.error(errorMessage, exception);
contribution.setExitStatus(FAILED);
itemProcessFailedNotifier.notifyByEmailOnException(chunkContext.getStepContext(), new Exception(errorMessage,
exception));
}
return RepeatStatus.FINISHED;
}
}
Please find my testcase
code for other than runtime exception
case.
@InjectMocks private NotifySupervisorJobTask notifySupervisorJobTask;
@Mock
private ItemProcessFailedNotifier itemProcessFailedNotifier;
@Mock
private CoreClient client;
private ChunkContext chunkContext;
private StepContext stepContext;
@Before
public void setUp() {
chunkContext = mock(ChunkContext.class);
stepContext = mock(StepContext.class);
when(chunkContext.getStepContext()).thenReturn(stepContext);
}
@Test(expected = Exception.class)
public void shouldThrowExceptionOtherThanRuntimeException() throws Exception {
Exception ex = mock(Exception.class);
doThrow(ex).when(client).notifySupervisor(null); // Line not covered
notifySupervisorJobTask.execute(null, chunkContext); // Line not covered
verify(itemProcessFailedNotifier).notifyByEmailOnException(stepContext, ex); // Line not covered
}
Solution
You can't tell Mockito to throw an exception which can't possibly be thrown by the mocked method.
In Java, you have checked and unchecked exceptions. Unchecked in your case are subclasses of RuntimeException
. Checked are all others (including the Exception
class itself), but they have to be either catched, or declared in the surrounding method signature.
Since your notifySupervisor
method obviously doesn't declare any checked exceptions (otherwise your execute
method wouldn't compile), Mockito can't go against the compiler and throw such an exception from its mock.
Answered By - Sergei
Answer Checked By - Clifford M. (JavaFixing Volunteer)