我正在为下面的Java代码编写Junit代码覆盖范围,而该代码未覆盖Otherthan Runtime Exception
。
请在下面找到我的Java代码。
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;
}
}
请为testcase
的情况找到我的other than runtime exception
代码。
@InjectMocks 私人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
}
答案 0 :(得分:1)
您不能告诉Mockito抛出模拟方法不可能抛出的异常。
在Java中,您已检查和未检查异常。在您的情况下,未经检查的是RuntimeException
的子类。已检查所有其他内容(包括Exception
类本身),但必须捕获它们,或在周围的方法签名中声明它们。
由于您的notifySupervisor
方法显然未声明任何已检查的异常(否则,您的execute
方法将无法编译),因此Mockito无法违背编译器并从其模拟中抛出此类异常