【问题标题】:How can I inject a testing value for a Spring Batch configuration class?如何为 Spring Batch 配置类注入测试值?
【发布时间】:2016-01-11 21:06:32
【问题描述】:

我有一个 Spring Boot / Batch 应用程序,想编写几个集成测试。该批次有一个 FlatFileItemReader 并通过 yml 配置文件拉入要读取的文件。这是批处理配置类:

@Configuration
@EnableBatchProcessing
public class BatchConfiguration { 

    @Value("${file}")
    private File file;

    @Bean
    public ItemReader<MyClass> reader(LineMapper<MyClass> lineMapper) {

        FlatFileItemReader<MyClass> flatFileItemReader = new FlatFileItemReader<MyClass>();
        flatFileItemReader.setResource(new FileSystemResource(file));
        final int NUMBER_OF_HEADER_LINES = 1;
        flatFileItemReader.setLinesToSkip(NUMBER_OF_HEADER_LINES);
        flatFileItemReader.setLineMapper(lineMapper);
        return flatFileItemReader;
    }

测试阅读器的集成测试类是:

@SpringApplicationConfiguration(classes = LoadApplication.class)
@TestExecutionListeners( { DependencyInjectionTestExecutionListener.class,
    StepScopeTestExecutionListener.class })
@RunWith(SpringJUnit4ClassRunner.class)
public class StepScopeTestExecutionListenerIntegrationTests {

    @Autowired
    private ItemReader<MyClass> reader;

    @Rule
    public TemporaryFolder testFolder = new TemporaryFolder();

    @Bean
    public StepExecution getStepExection() {
        StepExecution execution = MetaDataInstanceFactory.createStepExecution();
        return execution;
    }

    @Test
    public void testGoodData() throws Exception {

        try {
            File testFile = testFolder.newFile();
            PrintWriter writer = new PrintWriter(testFile, "UTF-8");
            writer.println("a,b,c");
            writer.println("1,2,3");
            writer.close();
            //ReflectionTestUtils.setField(someObject, "file", testFile);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        assertNotNull(reader.read());
    }

}

在上面的测试代码中, someObject 应该设置成什么?还是有其他方法可以注入测试文件?

【问题讨论】:

    标签: integration-testing spring-batch spring-test


    【解决方案1】:

    在调用 testGoodData 之前已经创建了读取器。只需覆盖在阅读器上设置的资源。

    即替换

    ReflectionTestUtils.setField(someObject, "file", testFile);
    

    用这行代码

    reader.setResource(new FileSystemResource(testFile));
    

    【讨论】:

      猜你喜欢
      • 2019-02-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-25
      • 1970-01-01
      • 2021-10-26
      • 2021-05-22
      • 1970-01-01
      • 2020-11-04
      相关资源
      最近更新 更多