”“在使用进行单步测试时如何模拟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
}
答案 0 :(得分:0)
请记住,只需使用:
@Mock JobExecution jobExecution
public void setUp(){
MockitoAnnotations.init(this);
}
不会将该模拟实例注入到您期望的位置,也不会将其声明为实例变量。
此代码很好,您无需在其顶部使用@RunWith(MockitoJunitRunner.class)
。
您需要做的是使用您的jobExecution
或@Test
方法手动注入/设置@Before
实例。