我正在尝试为我的批处理应用程序实现单元测试,并面临Spring Batch配置的问题。
当前依赖项版本:
Spring Boot 3.0.4
Spring Batch 5.0.0
我的作业配置类
@Configuration
public class BatchProcessor {
public static final String PRE_PROCESS_STEP = "pre-process-step";
@Autowired
protected PlatformTransactionManager transactionManager;
@Autowired
protected JobLauncher jobLauncher;
@Autowired
protected JobRepository jobRepository;
@Autowired
protected JobExplorer jobs;
protected String jobName;
@Bean
public Job runJob() throws Exception {
return new JobBuilder(jobName, jobRepository)
.start(preProcessStep())
.next(processStep())
.build();
}
@Bean
protected Step preProcessStep() {
return new StepBuilder(PRE_PROCESS_STEP, jobRepository)
.tasklet(preProcess(null), transactionManager)
.build();
}
protected Tasklet preProcess(@Value("#{jobParameters[inputfilename]}") String fileName) {
...
}
}
试验类别
@ExtendWith(MockitoExtension.class)
@SpringBatchTest
@JdbcTest
@SpringJUnitConfig(BatchProcessor.class)
@ActiveProfiles("test")
//@EnableBatchProcessing
public class BatchProcessorTest {
@Autowired
private JobLauncherTestUtils jobLauncherTestUtils;
@Autowired
private JobRepositoryTestUtils jobRepositoryTestUtils;
@Mock
private StepExecution stepExecution;
@Mock
private StepContribution stepContribution;
@Mock
private StepContext stepContext;
@Mock
private ChunkContext chunkContext;
private JobParameters setupJobParameters(String fileName) {
JobParametersBuilder paramsBuilder = new JobParametersBuilder();
paramsBuilder.addString("inputfilename", fileName);
return paramsBuilder.toJobParameters();
}
@Test
public void givenFileName_whenMatched_thenSuccess() throws Exception {
jobLauncherTestUtils.launchStep(BatchProcessor.PRE_PROCESS_STEP, setupJobParameters("XXX"));
}
}
使用此配置,我的测试失败,但有以下例外:
发生异常:没有类型为'org.springframework.batch.core.launch.JobLauncher'的合格Bean可用:应至少有1个Bean符合自动连接候选项的条件。依赖关系注解:{@org.springframework.beans.工厂.注解.自动连线(必需=真)}
参考Sping Boot 3.0迁移指南,从Spring Batch 5.0.0 @EnableBatchProcessing
annotation开始“告诉自动配置后退。
但是当我将@EnableBatchProcessing
添加回BatchProcessorTest
类时,它开始工作,但后来失败了:
原因:org.h2.jdbc.JdbcSQL语法错误异常:未找到表“BATCH_JOB_INSTANCE”(此数据库为空);SQL语句:从BATCH_JOB_INSTANCE中选择JOB_INSTANCE_ID、JOB_NAME,其中JOB_NAME =?且JOB_KEY =?
我尝试手动配置数据源
一个三个三个一个
但没有成功。
我没有为Spring应用程序编写单元测试的经验,也不知道如何解决这些问题。有人能给我建议吗?
先谢了。
1条答案
按热度按时间s4n0splo1#
刚刚发现我的错误。我已经添加了
@JdbcTest
注解来解决我之前的PlatformTransactionManager
bean问题。从我的测试类中删除了该注解,添加了mockPlatformTransactionManager
并删除了@EnableBatchProcessing
。最终工作版本为: