Spring Batch测试无法注入JobLauncherTestUtils、JobLauncher类型Bean
问题根因
你测试类中的@ContextConfiguration仅指定了自定义的MyBatchConfig配置类,没有加载Spring Boot原生的Batch自动配置类,导致JobLauncher、JobRepository这类Spring Batch核心Bean没有被初始化。而@SpringBatchTest注解依赖这些核心Bean才能生成对应的测试工具类Bean,因此会抛出找不到对应Bean的错误。
解决方案
方案1:使用@SpringBootTest注解(最简便,适配Spring Boot项目)
直接替换测试类上的原有注解,触发Spring Boot的全量自动配置即可,修改后的测试类代码如下:
@SpringBatchTest @SpringBootTest public class MyBatchConfigTest { @Autowired private JobLauncherTestUtils jobLauncherTestUtils; @Autowired private JobRepositoryTestUtils jobRepositoryTestUtils; @BeforeEach public void clearJobExecutions() { this.jobRepositoryTestUtils.removeJobExecutions(); } @Test public void testMyJob() throws Exception { JobParameters jobParameters = this.jobLauncherTestUtils.getUniqueJobParameters(); JobExecution jobExecution = this.jobLauncherTestUtils.launchJob(jobParameters); Assertions.assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); } }
@SpringBootTest会自动扫描项目配置、加载Spring Boot的默认自动配置逻辑,会直接使用你引入的H2依赖初始化嵌入式内存数据源作为Spring Batch的持久化存储,不需要额外配置数据源。
方案2:轻量上下文测试(仅加载必要配置)
如果你不想加载整个Spring Boot上下文,只保留最小测试依赖,可以在@ContextConfiguration中补充Batch相关的自动配置类:
@ExtendWith(SpringExtension.class) @SpringBatchTest @ContextConfiguration(classes = { MyBatchConfig.class, org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration.class, org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration.class, org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration.class, org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration.class }) public class MyBatchConfigTest { // 原有测试代码不需要修改 }
额外注意事项
注意:Spring Boot 2.4+版本的spring-boot-starter-batch默认会自动开启Batch配置,请勿在启动类手动添加@EnableBatchProcessing注解,否则会覆盖自动配置逻辑,导致核心Bean初始化异常。
内容的提问来源于stack exchange,提问作者Excite
相关产品推荐
相关产品推荐

