gpt4 book ai didi

java - 如何在mockito+Junit测试中捕获或模拟意外异常?

转载 作者:行者123 更新时间:2023-12-02 09:44:08 25 4
gpt4 key购买 nike

这是主文件中的函数,我需要为其编写测试。

@Override
public void processTask(JobExecutionContext arg0) throws TaskException {

if (BatchInputChannel.DB.toString().equals(runtimeContext.getProperties().getProperty(BATCH_CHANNEL_TYPE))) {
return;
} else if (BatchInputChannel.FILE.toString().equals(runtimeContext.getProperties().getProperty(BATCH_CHANNEL_TYPE))) {
jobLauncher = (JobLauncher) beanFactory.getBean("jobLauncher");
Job job = (Job) beanFactory.getBean("micorpFileLoadJob");
JobParameters jobParameters = new JobParametersBuilder()
.addLong("time", System.currentTimeMillis())
.toJobParameters();
try {
JobExecution jobExecution = jobLauncher.run(job, jobParameters);
System.out.println("jobExecution=="+jobExecution);
} catch (JobExecutionAlreadyRunningException | JobRestartException | JobInstanceAlreadyCompleteException
| JobParametersInvalidException e) {
throw new ProcessingException("File Loading Failed" + e.getMessage());
}
}
}

这是我尝试创建的测试函数

@Test(expected = JobParametersInvalidException.class)
public void processTaskWithFileInputJobFailed5() throws Exception {
when(mockruntimeContext.getProperties()).thenReturn(mockProperties);
when(mockProperties.getProperty(BATCH_CHANNEL_TYPE)).thenReturn("FILE");

when(mockbeanFactory.getBean("jobLauncher")).thenReturn(mockJobLauncher);
when(mockbeanFactory.getBean("micorpFileLoadJob")).thenReturn(mockjob);

mockjobParameters = new JobParametersBuilder().addLong("time", System.currentTimeMillis()).toJobParameters();
when(mockJobLauncher.run(mockjob, mockjobParameters)).thenReturn(mockJobExecution);
when(mockJobExecution.getStatus()).thenReturn(BatchStatus.FAILED);
when(mockJobExecution.getJobConfigurationName()).thenReturn(null);
Mockito.doThrow(new JobParametersInvalidException("Invalid")).when(mockJobLauncher).run(mockjob, mockjobParameters);
inputFileLoaderTaskProcessor.processTask(mockjobExecutionContext);
}

当我将项目作为 J 单元测试执行时,它期望抛出处理异常,但我在预期中提到了“JobParametersInvalidException”。

正如你所看到的,我在这个函数中只添加了一个异常,为了覆盖主函数中的所有异常(catch内部),需要做什么?

最佳答案

Mockito.doThrow(new JobParametersInvalidException("Invalid")).when(mockJobLauncher).run(mockjob, mockjobParameters);

由于参数不匹配,因此未调用此 doThrow。

代码中,参数设置方式为:

   JobParameters jobParameters = new JobParametersBuilder()
.addLong("time", System.currentTimeMillis())
.toJobParameters();

在单元测试中,匹配的模拟通过以下方式设置:

mockjobParameters = new JobParametersBuilder().addLong("time", System.currentTimeMillis()).toJobParameters();

问题是,在设置测试和执行测试代码之间,毫秒时钟几乎肯定会滴答作响。这意味着这些参数将不相等,因此不会引发异常。

更改模拟设置以期望任何 JobParameters,例如:

Mockito.doThrow(new JobParametersInvalidException("Invalid")).when(mockJobLauncher).run(eq(mockjob), any(JobParameters.class));

关于java - 如何在mockito+Junit测试中捕获或模拟意外异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56801004/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com