0

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

“我试过了

@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
}
4

1 回答 1

1

您记住,只需使用:

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

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

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

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

于 2019-02-01T10:37:52.980 回答