使用 Spring 启动测试批次

Test Batch with Spring boot

我创建了一个批次,一切正常 我做了一些单元测试,它也很好用 我正在尝试按照 spring-批处理文档对我的批处理进行集成测试,但我不明白我的错误。

这是我的批处理配置

@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;
   }

}

我的一批中的一个例子

@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);
    }
}

我的testConfiguration的配置

@SpringBootConfiguration
@EnableAutoConfiguration
public class TestConfig {
       public static void main(String[] args) {
           SpringApplication.run(Application.class, args);
       }
}

和测试

@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());
    }

}

我收到错误

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)}

我尝试添加到 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;
}

我得到了错误

>***************************
>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

我试图改变

@Qualifier("timeoutFormJob) Job job

来自

@Autowired TimeoutFormJob jobConfig; ... jobLauncherTestUtils.setJob(jobconfig.createJob());

但是我得到了

No qualifying bean of type 'a.b.c.batch.config.TimeoutFormJob' available

我不明白错误。我试图完全按照 spring 文档进行操作,但没有任何效果...... 我试图在 Whosebug 上找到解决方案,但我没有找到带有批处理声明注释的示例

#### EDIT

我删除一切从零开始

我查看了 SpringBatchTest 的文档并尝试了 id 但我遇到了其他一些错误 我必须添加 @EnableAutoConfiguration(即使我已经在 ConfigTest 中得到它)

我在 spring 文档中看到 @ContextConfiguration 添加作业 我必须添加批处理中使用的所有 reader/processor/writer/services/my 个映射器...

现在看起来像

@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());
    }

}

但是当添加 @ContextConfiguration 时,我不能再使用嵌入式数据库了...当我尝试坚持时,我得到了一个

Error: no transaction in progress

您需要在测试上下文中添加类型为 JobLauncherTestUtils 的 bean。类似于:

@Bean
public JobLauncherTestUtils jobLauncherTestUtils() {
    return new JobLauncherTestUtils();
}

作为记录,参考文档的 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 部分。

希望对您有所帮助。