简体   繁体   中英

StepBuilder.chunk() returning null with mockito

I have a Spring batch configuration class MyConfig with my reader, writer, step and Job beans. Below is my Step bean.

@Bean
public Step myStep() {
    return stepBuilderFactory.get(STEP_NAME).<MyType, MyType>chunk(getMinimumChunkSize())
            .reader(myReader)
            .writer(myWriter)
            .build();

}

When I try unit testing it with the below class

@RunWith(MockitoJUnitRunner.class)
@ContextConfiguration(classes = {MyConfig.class})
@TestExecutionListeners( { DependencyInjectionTestExecutionListener.class,
                StepScopeTestExecutionListener.class })
public class MyConfigTest {

    @Mock
    private StepBuilderFactory stepBuilderFactory;

    @Mock
    private StepBuilder stepBuilder;

    @Mock
    private SimpleStepBuilder simpleStepBuilder;

    @Mock
    FlatFileItemWriter myWriter;

    @Mock
    JdbcCursorItemReader myReader;

    @InjectMocks
    private MyConfig myConfig;

    @Before
    public void setUp() {
        when(stepBuilderFactory.get(anyString())).thenReturn(stepBuilder);
        when(stepBuilder.chunk(any())).thenReturn(simpleStepBuilder);
        when(simpleStepBuilder.reader(myReader)).thenReturn(simpleStepBuilder);
        when(simpleStepBuilder.writer(myWriter)).thenReturn(simpleStepBuilder);
    }

    @Test
    public void testChecklistStep() {
        final Step step = myConfig.checklistStep();
        assertNotNull(step);
    }      
}

On debug I get stepBuilderFactory.get(STEP_NAME) gives the mock as expected shown below

在此处输入图像描述

but the stepBuilderFactory.get(STEP_NAME).<MyType, MyType>chunk(getMinimumChunkSize()) is returning null instead of SimpleStepBuilder mock. This looks pretty straight forward, I am new to mockito and spring batch. Why is the thenReturn not working in this case?

I tried reading official documentation but this was of less help to what i am trying to do. Please suggest if my approach is wrong or if I'm missing anything?

That's because the chunk method creates a new step builder wrapping your mock: https://github.com/spring-projects/spring-batch/blob/master/spring-batch-core/src/main/java/org/springframework/batch/core/step/builder/StepBuilder.java#L69 . So stepBuilder.chunk(any()) is not the mock you think it is.

That said, I'm wondering why you need to mock StepBuilderFactory and StepBuilder anyway. Your test is testing that stepBuilder correctly creates a Step. Unless you do not trust Spring Batch code, you should not be doing this.

What you should be doing though is testing the actual business logic of your Step (correctly reading/writing data, its processing logic, etc).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM