使用 @MockBean Analoging JobExplorer 抛出异常:InstanceAlreadyExcep



>"如何在使用 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
}

请记住,只需使用:

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

不会导致将该模拟实例注入到预期位置或将其声明为实例变量的位置。

这段代码很好,你不需要在它上面使用@RunWith(MockitoJunitRunner.class)

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

相关内容

  • 没有找到相关文章

最新更新