spring-batch
spring-batch copied to clipboard
Do not autowire the Job inside JobLauncherTestUtils
Petar Tahchiev opened BATCH-2366 and commented
Hello,
I have several jobs defined. Then I want to test them so I create a bean of type JobLauncherTestUtils inside my config:
@Bean(name = "ncsvjobLauncherTestUtils")
public JobLauncherTestUtils defaultJobLauncherTestUtils() {
JobLauncherTestUtils result = new JobLauncherTestUtils();
result.setJob(context.getBean("ncsvImportJob", Job.class));
return result;
}
However when I run my tests I get this exception:
ption is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.springframework.batch.test.JobLauncherTestUtils.setJob(org.springframework.batch.core.Job); nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [org.springframework.batch.core.Job] is defined: expected single matching bean but found 3: ncsvImportJob,syncEntityJob,syncCatalogJob
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1202)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
This is because the JobLauncherTestUtils the setJob method has the @Autowired annotation so it will try to autowire the job, but as I said I have several.
2 votes, 3 watchers
Mariusz commented
Hi, you can just write:
// override method with name of your job bean
@Bean
public JobLauncherTestUtils getJobLauncherTestUtils() {
return new JobLauncherTestUtils() {
@Override
@Autowired
public void setJob(@Qualifier("ncsvImportJob") Job job) {
super.setJob(job);
}
};
}
Seems this this one is throwing a circular bean issue.
Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'MYJOB': Requested bean is currently in creation: Is there an unresolvable circular reference?
@SpringBatchTest @RunWith(SpringRunner.class) @ContextConfiguration(classes= Application.class) @SpringBootTest @Slf4j public class MyJobITTest {
JobLauncherTestUtils jobLauncherTestUtils;
// override method with name of your job bean
@Bean
public JobLauncherTestUtils getJobLauncherTestUtils() {
return new JobLauncherTestUtils() {
@Override
@Autowired
public void setJob(@Qualifier(MYJOB) Job job) {
super.setJob(job);
}
};
}
@Test
public void test() throws Exception {
jobLauncherTestUtils.launchJob();
}