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