I am currently working on a spring boot project that uses spring batch. I am trying to use JavaConfig instead of xml but it's difficult with all of the docs currently in xml.
I followed https://blog.codecentric.de/en/2013/06/spring-batch-2-2-javaconfig-part-5-modular-configurations but am having difficulties using the JobLauncherTestUtils. I know I need to tell the test to use the correct spring context, but I can't seem to figure out how to do it. I get the following error:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.batch.test.JobLauncherTestUtils' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
My test looks like the following:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {MyApplication.class, MyJobConfiguration.class})
public class RetrieveDividendsTest {
@Autowired
private JobLauncherTestUtils jobLauncherTestUtils;
@Test
public void testSomething() throws Exception {
jobLauncherTestUtils.launchJob();
}
}
I stumbled upon the same issue and had a look at this XML configuration from the Spring Batch samples. Based on that I managed to get it working with:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = { BatchTest.BatchTestConfig.class })
public class BatchTest {
@Autowired
private JobLauncherTestUtils jobLauncherTestUtils;
@Test
public void demo() throws Exception {
JobExecution jobExecution = jobLauncherTestUtils.launchJob();
Assert.assertEquals(BatchStatus.COMPLETED, jobExecution.getStatus());
}
@Configuration
@EnableBatchProcessing
static class BatchTestConfig {
@Bean
JobLauncherTestUtils jobLauncherTestUtils() {
return new JobLauncherTestUtils();
}
// rest omitted for brevity
}
}
The test succeeds and my ItemWriter logs the processed elements as expected.
For spring Batch 4.1.x or above Version We can use @SpringBatchTest annotation that will automatically inject jobLauncherTestUtils , check sample example for more details Here
This is how you can created if u cant upgrade to 4.1.x or above
@Bean
public JobLauncherTestUtils getJobLauncherTestUtils(){
return new JobLauncherTestUtils() {
@Override
@Autowired
public void setJob(@Qualifier("myjobname") Job job) {
super.setJob(job);
}
};
}
Do you have the following in your pom.xml?
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
</dependency>
If I'm not mistaken, and you use spring boot, it should load the auto-configuration beans of spring batch for you so they will be available for injection.