Locke
Locke

Reputation: 544

How to test a single step in Spring Batch without running others?

I have a spring batch application with a single job that runs two steps. I would like to be able to test each step individually without having to run the other. Is this possible? My code is as follows:

@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());
}

But when I run the test above it essentially launches and runs my entire job from front to back.

Upvotes: 2

Views: 4837

Answers (1)

adam
adam

Reputation: 113

Assuming that you're running JUnit test cases, you can use the JobLauncherTestUtils to launch a specific step. You'll also need to create an ExecutionContext instance via the MetaDataInstanceFactory, which is passed to the JobLauncherTestUtils.launchStep() method.

@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);
    }
}

Hope that helps!

Upvotes: 2

Related Questions