我有这个测试班:

@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("myJob"), eq(simpleJob));

}


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

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

[MockitoHint] ... args好吗? ->在...
 但我不明白为什么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);
}

最佳答案

更改设置以接受非any(Job.class)的任何类:

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

关于java - 方法不起作用时的Mockito [MockitoHint] 1.未使用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54788892/

10-11 20:41