方法不起作用时的Mockito [MockitoHint] 1.未使用

时间:2019-02-20 14:41:29

标签: java spring unit-testing mockito spring-batch

我有这个测试班:

@RunWith(MockitoJUnitRunner.class)  
public class JobServiceTests {

@InjectMocks
private ServiceImpl subject;

@Mock
private ApplicationContext applicationContext;

@Mock
private JobLauncher jobLauncher;

@Mock
private JobExplorer jobExplorer;



@Test
public void test() throws Exception {
    final SimpleJob simpleJob = new SimpleJob();
    simpleJob.setName("nameJob");

    when(applicationContext.getBean(any(String.class), any(Job.class))).thenReturn(simpleJob);

    final JobParameters jobLauncherParam = ImtJobParameters.builder()
            .addParameter("p1", "v1", true)
            .build();

    final BatchJobExec jobExec = subject.launchBatchJob("nameJob", jobLauncherParam);
    assertThat(jobExec.id).isEqualTo(100L);


    final JobParametersBuilder jobParametersBuilder = new JobParametersBuilder();
    jobParametersBuilder.addString("param1", "val1", true);
    final JobParameters jobParams = jobParametersBuilder.toJobParameters();

    verify(applicationContext, only()).getBean(eq("archpurjJob"), eq(simpleJob));

}

运行测试时,请获取NullPointerException,因为jobExec为空且

[MockitoHint] 1.未使用...->在...

[MockitoHint] ...可以吗? ->在...  但我不明白为什么when(applicationContext.getBean(any(String.class), any(Job.class))).thenReturn(simpleJob);无法正常工作...

方法launchBatchJob

  public BatchJobExec launchBatchJob(final String jobName, final JobLaunchParameters jobLaunchPayload) {
    Job job;
    try {
        job = applicationContext.getBean(jobName, Job.class);
    } catch (final BeansException e) {
        throw new BatchJobNotFoundException(String.format("Batch Job  with name %s not found", jobName), e);
    }

    JobExecution jobExecution;
    try {
        jobExecution = jobLauncher.run(job, createJobParameters(jobLaunchPayload.getParameters()));
    } catch (//
            JobExecutionAlreadyRunningException //
            | JobRestartException //
            | JobInstanceAlreadyCompleteException //
            | JobParametersInvalidException e) {
        LOG.error(String.format("Failed to launch job %s", jobName), e);
        throw new BatchJobLaunchException(//
                String.format("Failed to launch job %s", jobName), //
                e);
    }

    return jobExecutionMapper.mapJobExecutionToImtBatchJobExec(jobExecution);
}

1 个答案:

答案 0 :(得分:0)

更改设置以接受除any(Job.class)以外的任何课程:

when(applicationContext.getBean(any(String.class), any(Class.class))).thenReturn(simpleJob);