You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Batch单元测试报错:No Scope registered for scope name 'step' 求解决

问题描述

我有一个名为CollectionUtility的组件类,使用@StepScope并注入了JobParameter值:

@Component
@StepScope
public class CollectionUtility {
    @Value("#{jobParameters['jobStartTime']}")
    private Long jobStartTime;

    // 假设包含getCollectionName方法
    public String getCollectionName() {
        // 业务逻辑返回"Random_Sample"
        return "Random_Sample";
    }
}

编写单元测试时使用了@SpringBatchTest和StepScopeTestUtils,测试代码如下:

@SpringBatchTest
@SpringJUnitConfig(CollectionUtility.class)
class CollectionUtilityTest {

    @Autowired
    private CollectionUtility collectionUtility;

    @Test
    void getCollectionName() throws Exception {
        JobParameters jobParameters = new JobParametersBuilder()
                .addLong("jobStartTime", System.currentTimeMillis())
                .toJobParameters();
        StepExecution stepExecution = MetaDataInstanceFactory.createStepExecution(jobParameters);
        String collectionName = StepScopeTestUtils.doInStepScope(stepExecution,() -> collectionUtility.getCollectionName());
        assertEquals("Random_Sample", collectionName);
    }
}

运行测试时抛出错误:

java.lang.IllegalStateException: No Scope registered for scope name 'step'
解决方法

原因

@StepScope是Spring Batch提供的自定义作用域,需要对应的StepScope Bean被注册到Spring容器中才能生效。之前的测试仅注册了CollectionUtility类,未引入Spring Batch的基础配置,导致容器中没有注册StepScope,从而抛出异常。

方案1:手动注册StepScope(通用方式)

创建测试配置类,手动注册StepScope Bean:

@Configuration
public class BatchTestConfig {
    @Bean
    public static StepScope stepScope() {
        StepScope stepScope = new StepScope();
        stepScope.setAutoProxy(true); // 开启自动代理,确保作用域生效
        return stepScope;
    }
}

修改测试类,将配置类加入到@SpringJUnitConfig中:

@SpringBatchTest
@SpringJUnitConfig(classes = {CollectionUtility.class, BatchTestConfig.class})
class CollectionUtilityTest {

    @Autowired
    private CollectionUtility collectionUtility;

    @Test
    void getCollectionName() throws Exception {
        JobParameters jobParameters = new JobParametersBuilder()
                .addLong("jobStartTime", System.currentTimeMillis())
                .toJobParameters();
        StepExecution stepExecution = MetaDataInstanceFactory.createStepExecution(jobParameters);
        
        String collectionName = StepScopeTestUtils.doInStepScope(stepExecution, collectionUtility::getCollectionName);
        assertEquals("Random_Sample", collectionName);
    }
}

方案2:引入Spring Batch自动配置(Spring Boot项目)

如果是Spring Boot项目,可直接引入BatchAutoConfiguration,它会自动注册StepScope及其他Spring Batch基础组件:

@SpringBatchTest
@SpringJUnitConfig(classes = {CollectionUtility.class, BatchAutoConfiguration.class})
class CollectionUtilityTest {
    // 测试代码与原代码一致
}

内容的提问来源于stack exchange,提问作者devincrisis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 19:50:01