Issue
I create a batch and everything work well I do some unittest and it's work well too I'm trying to do integration test my batch following spring-batch documentation but i don't understand my errors.
Here my batch config
@Configuration
@EnableBatchProcessing
@EnableScheduling
@EnableTransactionManagement
@PropertySource(value="/batch.properties", ignoreResourceNotFound = false)
public class BatchConfiguration {
@Autowired
DataSource dataSource;
@Autowired
PlatformTransactionManager transactionManager;
@Bean
public JobRepository jobRepository() throws Exception {
JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean();
factory.setDataSource(dataSource);
factory.setTransactionManager(transactionManager);
factory.afterPropertiesSet();
return (JobRepository) factory.getObject();
}
@Bean
public SimpleJobLauncher jobLauncher(JobRepository jobRepository) {
SimpleJobLauncher launcher = new SimpleJobLauncher();
launcher.setJobRepository(jobRepository);
return launcher;
}
}
a example of one of my batch
@Component
@AutomaticLogging
public class TimeoutFormJob {
@Autowired
public JobBuilderFactory jobBuilderFactory;
@Autowired
public StepBuilderFactory stepBuilderFactory;
@Autowired
private SimpleJobLauncher jobLauncher;
@Value("${batch.timeoutForm.chunk}")
int chunk;
@Autowired
TimeoutFormReader reader;
@Autowired
TimeoutFormProcessor processor;
@Autowired
public TimeoutFormWriter writer;
@Bean
public Step createStep() {
return stepBuilderFactory.get("timeoutFormStep").<MyFormEntity, MyFormEntity>chunk(chunk).reader(reader).processor(processor).writer(writer).build();
}
@Bean
public Job createJob() {
return jobBuilderFactory.get("timeoutFormJob").incrementer(new RunIdIncrementer()).flow(createStep()).end().build();
}
@Scheduled(cron = "${batch.timeoutForm.cron}")
public void perform() throws Exception {
JobParameters param = new JobParametersBuilder().addString("JobID", String.valueOf(System.currentTimeMillis())).toJobParameters();
jobLauncher.run(createJob(), param);
}
}
The configuration of my testConfiguration
@SpringBootConfiguration
@EnableAutoConfiguration
public class TestConfig {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
and the test
@RunWith(SpringJUnit4ClassRunner.class)
@DataJpaTest
public class TimeoutFormJobTest {
@Autowired
private JobLauncherTestUtils jobLauncher;
@Test
public void testIntegration_batch() throws Exception {
assertEquals(1, myService.findFormNotfinish().size());
jobLauncher.launchJob();
assertEquals(0, myService.findFormNotfinish().size());
}
}
I got error
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'a.b.c.batch.TimeoutFormJobTest': Unsatisfied dependency expressed through field 'jobLauncher'; nested exception is 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)}
I tried to add to the ConfigTest
@Autowired
DataSource dataSource;
@Autowired
PlatformTransactionManager transactionManager;
@Autowired
SimpleJobLauncher jobLaucher;
@Autowired
JobRepository jobRepository;
@Autowired
@Qualifier("timeoutFormJob")
Job job;
@Bean
public SimpleJobLauncher jobLauncher(JobRepository jobRepository) {
SimpleJobLauncher launcher = new SimpleJobLauncher();
launcher.setJobRepository(jobRepository);
return launcher;
}
@Bean
public JobRepository jobRepository() throws Exception {
JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean();
factory.setDataSource(dataSource);
factory.setTransactionManager(transactionManager);
factory.afterPropertiesSet();
return (JobRepository) factory.getObject();
}
@Bean
public JobLauncherTestUtils getJobLauncherTestUtils(){
JobLauncherTestUtils jobLauncherTestUtils = new JobLauncherTestUtils();
jobLauncherTestUtils.setJob(job);
jobLauncherTestUtils.setJobRepository(jobRepository);
jobLauncherTestUtils.setJobLauncher(jobLaucher);
return jobLauncherTestUtils;
}
and i got the error
>***************************
>APPLICATION FAILED TO START
>***************************
>Description:
>
>Field job in a.b.c.Application >required a bean of type 'org.springframework.batch.core.Job' that could not be >found.
>
>Action:
>Consider defining a bean of type 'org.springframework.batch.core.Job' in your >configuration
I tried to change the
@Qualifier("timeoutFormJob)
Job job
by
@Autowired
TimeoutFormJob jobConfig;
...
jobLauncherTestUtils.setJob(jobconfig.createJob());
But i got
No qualifying bean of type 'a.b.c.batch.config.TimeoutFormJob' available
I don't understand error. I tried to follow exactly the spring documentation and nothing works... I tried to find solution on stackoverflow but i don't find example with batch declaration annotation
#### EDIT
I remove everything to start from zero
I looked the doc of SpringBatchTest and tried id but i got other few error I must add @EnableAutoConfiguration (even if i already got it in ConfigTest)
And i saw in the spring doc the @ContextConfiguration to add the Job I must add all reader/processor/writer/services/my mappers used in the batch...
now it look like
@RunWith(SpringJUnit4ClassRunner.class)
@DataJpaTest
@Sql({"classpath:org/springframework/batch/core/schema-drop-h2.sql", "classpath:org/springframework/batch/core/schema-h2.sql"})
@SpringBatchTest
@ContextConfiguration(classes = {BatchConfiguration.class, TimeoutFormJob.class, Reader.class, Processor.class, Writer.class, ServiceA.class, MapperA.class, HelperMapper.class, ServiceB.class})
@EnableAutoConfiguration
public class TestBatch {
@Autowired
private JobLauncherTestUtils jobLauncherTestUtils;
@Autowired
private TestEntityManager entityManager;
@Autowired
private MyRepo myRepo;
@Test
public void myBatchTest() {
assertEquals(0, myRepo.findAll().size());
entityManager.persist(new MyEntity());
assertEquals(1, myRepo.findAll().size());
JobExecution jobExecution = jobLauncherTestUtils.launchJob();
Assert.assertEquals("COMPLETED", jobExecution.getExitStatus().getExitCode());
assertEquals(0, myRepo.findAll().size());
}
}
But when addind @ContextConfiguration I can't use embedded database anymore... when i try to persist i got an
Error: no transaction in progress
Solution
You need to add a bean of type JobLauncherTestUtils
in your test context. Something like:
@Bean
public JobLauncherTestUtils jobLauncherTestUtils() {
return new JobLauncherTestUtils();
}
For the record, Spring Batch v4.1 introduced a new annotation called @SpringBatchTest
that automatically adds the JobLauncherTestUtils
to your context. For more details, please refer to the Creating a Unit Test Class section of the reference documentation.
Hope this helps.
Answered By - Mahmoud Ben Hassine