RunTimeException 以外的代码覆盖率未覆盖

我正在为下面的 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

 }


料青山看我应如是
浏览 123回答 1
1回答

互换的青春

您不能告诉 Mockito 抛出模拟方法不可能抛出的异常。在 Java 中,您有已检查和未检查的异常。在您的情况下,未选中的是RuntimeException. 检查所有其他(包括Exception类本身),但它们必须被捕获或在周围的方法签名中声明。由于您的notifySupervisor方法显然没有声明任何已检查的异常(否则您的execute方法将无法编译),Mockito 不能违背编译器并从其模拟中抛出这样的异常。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java