使用jobLauncherTestUtils进行Spring批处理集成测试

时间:2018-09-24 07:54:02

标签: spring spring-boot spring-batch

我正在尝试为批处理项目编写集成测试。

我的集成测试定义:

https://github.com/cristianprofile/spring-batch-testing/blob/master/src/test/java/test/BatchApplicationTests.java

@RunWith(SpringRunner.class)
@SpringBootTest

/* @Autowired
private JobLauncherTestUtils jobLauncherTestUtils;*/

public class BatchApplicationTests {

private static final String EXPECTED_FILE = "src/test/resources/users.csv";
private static final String OUTPUT_FILE = "src/main/resources//users.csv";
private static final String EXPECTED_FILE2 = "src/test/resources/users2.csv";
private static final String OUTPUT_FILE2 = "src/main/resources//users2.csv";

@Test
public void contextLoads()  throws Exception{
    System.out.println("Fake test ");
//      JobExecution jobExecution = jobLauncherTestUtils.launchJob();
//        JobExecution jobExecution = jobLauncherTestUtils.launchStep("step1");
//      Assert.assertEquals("COMPLETED",    jobExecution.getExitStatus().getExitCode());
//
//
//       AssertFile.assertFileEquals(new FileSystemResource(EXPECTED_FILE),
//                new FileSystemResource(OUTPUT_FILE));
//
//        AssertFile.assertFileEquals(new FileSystemResource(EXPECTED_FILE2),
//                new FileSystemResource(OUTPUT_FILE2));

}

Spring配置测试文件夹:

package test;

import com.mymoid.batch.configuration.BatchConfiguration;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Import;

 @SpringBootConfiguration
 @EnableAutoConfiguration
 @Import({BatchTestConfig.class, BatchConfiguration.class})
 public class TestServiceConfigIT {
 }

BatchTestConfig类:

@Configuration
public class BatchTestConfig {

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

}

BatchConfiguration.class:

@Configuration
@EnableBatchProcessing
public class BatchConfiguration {

@Autowired
public JobBuilderFactory jobBuilderFactory;

@Autowired
public StepBuilderFactory stepBuilderFactory;

@Autowired
public DataSource dataSource;

@Bean
public JdbcCursorItemReader<User> reader(){
    JdbcCursorItemReader<User> reader = new JdbcCursorItemReader<User>();
    reader.setDataSource(dataSource);
    reader.setSql("SELECT id,name FROM user");
    reader.setRowMapper(new UserRowMapper());
    return reader;
}



@Bean
public UserItemProcessor processor(){
    return new UserItemProcessor();
}

@Bean
public FlatFileItemWriter<User> writer(){
    FlatFileItemWriter<User> writer = new FlatFileItemWriter<User>();

    final FileSystemResource fileSystemResource = new FileSystemResource("/Users/mymoid/projects/batch/src/main" +
            "/resources/users.csv");

    FlatFileHeaderCallback prueba= new FlatFileHeaderCallback() {
        @Override
        public void writeHeader(Writer writer) throws IOException {
            writer.write("columna1,cloumna2");
        }
    };
    writer.setHeaderCallback(prueba);
    writer.setResource(fileSystemResource);
    writer.setLineAggregator(new DelimitedLineAggregator<User>() {{
        setDelimiter(",");
        setFieldExtractor(new BeanWrapperFieldExtractor<User>() {{
            setNames(new String[] { "address.id", "address.name" });
        }});
    }});

    return writer;
}


@Bean
public FlatFileItemWriter<User> writer2(){
    FlatFileItemWriter<User> writer = new FlatFileItemWriter<User>();
    final FileSystemResource fileSystemResource = new FileSystemResource("/Users/mymoid/projects/batch/src/main" +
            "/resources/users2.csv");

    FlatFileHeaderCallback prueba= new FlatFileHeaderCallback() {
        @Override
        public void writeHeader(Writer writer) throws IOException {
            writer.write("columna1");
        }
    };
    writer.setHeaderCallback(prueba);
    writer.setResource(fileSystemResource);
    writer.setLineAggregator(new DelimitedLineAggregator<User>() {{
        setDelimiter(",");
        setFieldExtractor(new BeanWrapperFieldExtractor<User>() {{
            setNames(new String[] { "id"});
        }});
    }});

    return writer;
}




@Bean
public CompositeItemWriter compositeItemWritercomposite(){
    FlatFileItemWriter<User> writer = new FlatFileItemWriter<User>();
    writer.setResource(new ClassPathResource("users2.csv"));
    writer.setLineAggregator(new DelimitedLineAggregator<User>() {{
        setDelimiter(",");
        setFieldExtractor(new BeanWrapperFieldExtractor<User>() {{
            setNames(new String[] { "id"});
        }});
    }});

    final FlatFileItemWriter writer1 = writer();
    final FlatFileItemWriter<User>  userFlatFileItemWriter = writer2();
    List<ItemWriter<User>> writers = new ArrayList<>(2);
    writers.add(writer1);
    writers.add(userFlatFileItemWriter);
    CompositeItemWriter itemWriter = new CompositeItemWriter();

    itemWriter.setDelegates(writers);
    return itemWriter;
}


@Bean OrderWriter orderWriter()
{
   return new OrderWriter();
}







@Bean
public Step step1() {
    return stepBuilderFactory.get("step1").<User, User> chunk(2)
            .reader(reader())
            .processor(processor())
            .writer(compositeItemWritercomposite())
            .build();
}

@Bean
public Job exportUserJob() {
    return jobBuilderFactory.get("exportUserJob")
            .incrementer(new RunIdIncrementer())
            .flow(step1())
            .end()
            .build();
}

}

当我运行contextLoads(测试用例为空)时,Spring的运行方式与我运行主程序时的运行方式相同。如果我的代码的每一行都被注释,为什么Spring会批量运行?

enter image description here

2 个答案:

答案 0 :(得分:1)

SpringBootTest注释的javadoc

  

在不使用嵌套@Configuration且未指定显式类的情况下自动搜索@SpringBootConfiguration。

在测试类中,您没有使用@contextConfiguration或指定从哪个类加载应用程序上下文。因此,Spring Boot自动搜索Spring Boot配置,它会为您找到批处理作业配置并运行它。

您可以通过将spring.batch.job.enabled=false添加到application.properties文件中来禁用此功能。

答案 1 :(得分:0)

我刚刚解决了这个问题,给此application.properties(测试资源内部)的值赋了错误的值:

GROUP_CONCAT()

在此处查看完整的应用程序属性文件: https://github.com/cristianprofile/spring-batch-testing/blob/master/src/test/resources/application.properties