我有一个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应该设置为什么?或者是否有其他方法来注入测试文件?
答案 0 :(得分:0)
在调用testGoodData之前已经创建了读者。只需覆盖在阅读器上设置的资源。
即,替换
HOME
使用这行代码
ReflectionTestUtils.setField(someObject, "file", testFile);