如何测试Spring Batch中的单个步骤而不运行其他步骤?

时间:2017-02-15 22:43:34

标签: java spring spring-batch

我有一个弹出批处理应用程序,其中包含一个运行两个步骤的作业。我希望能够单独测试每个步骤而不必运行另一个步骤。这可能吗?我的代码如下:

@Bean
public Job job() throws Exception {
    return jobs.get("job")
            .incrementer(new RunIdIncrementer())
            .listener(new JobCompletionNotificationListener())
            .start(A)
            .next(B)
            .build();
}


@Test
public void testStepA() {
    JobExecution execution = launcher.launchStep("A");
    assertEquals(BatchStatus.COMPLETED, execution.getStatus());
}

但是当我在上面进行测试时,它基本上会启动并从前到后运行我的整个工作。

1 个答案:

答案 0 :(得分:0)

假设您正在运行JUnit测试用例,可以使用JobLauncherTestUtils启动特定步骤。您还需要通过MetaDataInstanceFactory创建一个ExecutionContext实例,该实例将传递给JobLauncherTestUtils.launchStep()方法。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:/batch/test-job.xml" })
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, StepScopeTestExecutionListener.class })
public class StepTest {
     @Autowired
     private JobLauncherTestUtils jobLauncherTestUtils;
     private JobExecution jobExecution;
     public ExecutionContext getExecutionContext() {
       return MetaDataInstanceFactory.createJobExecution().getExecutionContext();
    }

    @Test
    @DirtiesContext
    public void testStep() {
        ExecutionContext executionContext = getExecutionContext();
        jobExecution = jobLauncherTestUtils.launchStep(<STEP_NAME>, <JOB_PARAMS>, executionContext);
    }
}

希望有所帮助!