Spring-Batch:测试Step Scoped Step

我正在尝试测试Spring Batch步骤 . 我有2个场景要测试1.使用tasklet步骤(步骤作用域)2 . 使用ItemReader / ItemWriter(步骤范围)

我的测试类注释如下

@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({DependencyInjectionTestExecutionListener.class, StepScopeTestExecutionListener.class})
@ContextConfiguration(loader = SpringApplicationContextLoader.class, classes = ItemReturnsApplication.class)

This is how my test class looks like

@Bean
    JobLauncherTestUtils jobLauncherTestUtils(){
        return new JobLauncherTestUtils();
    }

    @Autowired
    private JobLauncherTestUtils jobLauncherTestUtils;

@Test
    public void testLaunchJob() throws Exception{
        JobExecution jobExecution = jobLauncherTestUtils.launchJob(
                new JobParametersBuilder().addString("chunkSize", "3").addString("current_date","2016-11-25").toJobParameters()
        );
        commonAssertions(jobLauncherTestUtils.launchJob());
        assertEquals(BatchStatus.COMPLETED, jobExecution.getStatus());
    }

当我运行测试用例时,进程失败,因为作业参数没有传递到我的作业中 .

我正在寻找在 Spring 季批次中测试Step Scoped步骤的正确方法 .

谢谢,Opensource Explorer

回答(1)

2 years ago

您当前的代码尝试启动并测试 a job and not a step . 根据Spring批处理documentation关于如何测试各个步骤,如何测试tasklet并将上下文注入到tasklet中的一个简单示例更符合以下代码:

@ContextConfiguration
@TestExecutionListeners( { DependencyInjectionTestExecutionListener.class,
    StepScopeTestExecutionListener.class })
@RunWith(SpringJUnit4ClassRunner.class)
public class StepScopeTestExecutionListenerIntegrationTests {

    // This component is defined step-scoped, so it cannot be injected unless
    // a step is active...
    @Autowired
    private YourTaskletClass yourTaskletClass;

    public StepExecution getStepExection() {
        StepExecution execution = MetaDataInstanceFactory.createStepExecution();
        execution.getExecutionContext().putString("input.data", "foo,bar,spam");
        return execution;
    }

    @Test
    public void testYourTaskletClass() {
        // The tasklet is initialized and some configuration is already set by the MetaDatAInstanceFactory           
        assertNotNull(yourTaskletClass.doSomething());
    }

}

只有1.4及更高版本的spring boot版本才能使用 @RunWith(SpringJUnit4ClassRunner.class) 注释 . 有关更多信息,请参阅this blog .

要启动单个步骤,请尝试将代码调整为:

@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({DependencyInjectionTestExecutionListener.class, StepScopeTestExecutionListener.class})
@ContextConfiguration(loader = SpringApplicationContextLoader.class, classes = ItemReturnsApplication.class)    
public class StepIntegrationTest {

    @Autowired
    private JobLauncherTestUtils jobLauncherTestUtils;

    @Test
    public void testLaunchJob() throws Exception{
       JobExecution jobExecution = jobLauncherTestUtils.launchStep("nameOfYourStep");

    } 
}