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

如何在JUnit 5 Mockito中Mock Spring Batch SimpleStepBuilder的processor()

在JUnit 5 Mockito中正确Mock Spring Batch SimpleStepBuilder的processor()方法

空指针异常原因

你的step()方法采用链式调用,从stepBuilderFactory.get()开始,后续chunk()、reader()、processor()等方法都会返回对应的Builder实例。如果没有逐层Mock这些Builder对象,调用processor()时会因前置步骤返回null触发空指针。

正确Mock的实现示例

需要Mock链式调用中的每一个Builder对象,以及相关的Item组件,确保每一步链式调用都返回Mock实例。以下是完整测试代码:

@ExtendWith(MockitoExtension.class)
class StepConfigurationTest {

    // Mock核心依赖
    @Mock
    private StepBuilderFactory stepBuilderFactory;

    @Mock
    private ItemReader<Object> testReader;

    @Mock
    private ItemProcessor<Object, Object> testProcessor;

    @Mock
    private ItemWriter<Object> testWriter;

    // Mock链式调用的各个Builder对象
    @Mock
    private SimpleStepBuilder<Object, Object> simpleStepBuilder;

    @Mock
    private ChunkOrientedStepBuilder<Object, Object> chunkStepBuilder;

    // 注入包含step()方法的待测试类
    @InjectMocks
    private YourStepConfig stepConfig;

    @Test
    void testStepCreation() {
        // 逐层配置链式调用的Mock返回值
        when(stepBuilderFactory.get(anyString())).thenReturn(simpleStepBuilder);
        // 匹配chunk方法的参数,用anyInt()适配任意分块大小
        when(simpleStepBuilder.<Object, Object>chunk(anyInt())).thenReturn(chunkStepBuilder);
        // 每个组件设置后返回自身Builder,保证链式调用不中断
        when(chunkStepBuilder.reader(testReader)).thenReturn(chunkStepBuilder);
        when(chunkStepBuilder.processor(testProcessor)).thenReturn(chunkStepBuilder);
        when(chunkStepBuilder.writer(testWriter)).thenReturn(chunkStepBuilder);
        // 最后build()返回Mock的Step实例
        when(chunkStepBuilder.build()).thenReturn(Mockito.mock(Step.class));

        // 调用目标方法
        Step resultStep = stepConfig.step();

        // 验证processor方法是否被正确调用
        verify(chunkStepBuilder).processor(testProcessor);
        assert resultStep != null;
    }
}

关键注意事项

  • 逐层Mock Builder:链式调用的每一步(get()→chunk()→reader()等)都要指定返回Mock的Builder实例,不能跳过任何环节。
  • 泛型匹配:Mockchunk()方法时要显式指定泛型<Object, Object>,避免类型不匹配导致Mock失效。
  • 参数匹配:如果chunk()方法有具体参数(如chunk(10)),可以用eq(10)替代anyInt()实现精准匹配。
  • 组件Mock:确保ItemReader、ItemProcessor、ItemWriter都被正确Mock,避免注入null。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 18:37:12