我正在為下面的 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;@Mockprivate ItemProcessFailedNotifier itemProcessFailedNotifier;@Mockprivate CoreClient client;private ChunkContext chunkContext;private StepContext stepContext;@Beforepublic 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 }
1 回答

互換的青春
TA貢獻1797條經驗 獲得超6個贊
您不能告訴 Mockito 拋出模擬方法不可能拋出的異常。
在 Java 中,您有已檢查和未檢查的異常。在您的情況下,未選中的是RuntimeException
. 檢查所有其他(包括Exception
類本身),但它們必須被捕獲或在周圍的方法簽名中聲明。
由于您的notifySupervisor
方法顯然沒有聲明任何已檢查的異常(否則您的execute
方法將無法編譯),Mockito 不能違背編譯器并從其模擬中拋出這樣的異常。
添加回答
舉報
0/150
提交
取消