使用@MockBean模拟JobExplorer引发异常:InstanceAlreadyException

时间:2019-02-01 10:24:41

标签: java spring junit mockito spring-batch-tasklet

”“在使用进行单步测试时如何模拟JobExecution   JobLauncherTestUtils?”

“我尝试过

@MockBean JobExplorer jobExplorer 

但它抛出异常:

Failed to load applicationContext,Caused by InstanceAlreadyExistsException

但是当我单独运行它时效果很好。所以我尝试使用

@Mock JobExplorer jobExplorer;
public void setUp(){
    MockitoAnnotations.init(this);
}

但是这个甚至不起作用:(然后我补充了

@RunWith(MockitoJunitRunner.class)
@Configuartion(...)
class MockTest{
@Mock JobExplorer jobExplorer
public void setUp(){
    MockitoAnnotations.init(this);
}

}

主要代码:


@RunWith(SpringRunner.class)
@Configuration(classes=TestConfig.class)
Class MockTest{
   private static final String jobName ="job";
   @Autowired JobLauncherTestUtils;
   @Autowired JobRegistry jobRegistry;
   @MockBean JobExplorer jobExplorer;
@Before
public void setUp(){
   Job job = jobRegistry.getJob(jobName);
   JobInstance jobInstance = new JobInstance(0L,job.getName());
   JobExecution jobExecution = new JobExecution(0L);
   jobExecution.setJobInstance(jobInstance);
}
@Test
public testMock(){
   //jobParams
   Data data = new Data();
   ExecutionContext context = new ExecutionContext();
   context.put("data",Data);
   jobExecution.setExecutionContext(context);
   when(jobExplorer.getJobExecution(any()).thenReturn(jobExecution);
   JobExecution jobExecution = testUtils.launchStep("stepname",context);
}
@After
public void tearDown(){
//statements
}

1 个答案:

答案 0 :(得分:0)

请记住,只需使用:

@Mock JobExecution jobExecution
public void setUp(){
    MockitoAnnotations.init(this);
}

不会将该模拟实例注入到您期望的位置,也不会将其声明为实例变量。

此代码很好,您无需在其顶部使用@RunWith(MockitoJunitRunner.class)

您需要做的是使用您的jobExecution@Test方法手动注入/设置@Before实例。