Annotation Interface SpringBatchTest
@Target(TYPE)
@Retention(RUNTIME)
@Documented
@Inherited
@TestExecutionListeners(listeners={StepScopeTestExecutionListener.class,JobScopeTestExecutionListener.class},
mergeMode=MERGE_WITH_DEFAULTS)
@ExtendWith(org.springframework.test.context.junit.jupiter.SpringExtension.class)
public @interface SpringBatchTest
Annotation that can be specified on a test class that runs Spring Batch based tests.
Provides the following features over the regular Spring TestContext Framework:
- Registers a
JobLauncherTestUtilsbean with theBatchTestContextCustomizer.JOB_LAUNCHER_TEST_UTILS_BEAN_NAMEwhich can be used in tests for launching jobs and steps. - Registers a
JobRepositoryTestUtilsbean with theBatchTestContextCustomizer.JOB_REPOSITORY_TEST_UTILS_BEAN_NAMEwhich can be used in tests setup to create or remove job executions. - Registers the
StepScopeTestExecutionListenerandJobScopeTestExecutionListeneras test execution listeners which are required to test step/job scoped beans.
A typical usage of this annotation with JUnit 4 is like:
@RunWith(SpringRunner.class)
@SpringBatchTest
@ContextConfiguration(classes = MyBatchJobConfiguration.class)
public class MyBatchJobTests {
@Autowired
private JobLauncherTestUtils jobLauncherTestUtils;
@Autowired
private JobRepositoryTestUtils jobRepositoryTestUtils;
@Autowired
private Job jobUnderTest;
@Before
public void setup() {
this.jobRepositoryTestUtils.removeJobExecutions();
this.jobLauncherTestUtils.setJob(this.jobUnderTest);
}
@Test
public void testMyJob() throws Exception {
// given
JobParameters jobParameters = this.jobLauncherTestUtils.getUniqueJobParameters();
// when
JobExecution jobExecution = this.jobLauncherTestUtils.launchJob(jobParameters);
// then
Assert.assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus());
}
}
For JUnit 5, this annotation can be used without having to manually register the
SpringExtension since @SpringBatchTest is meta-annotated with
@ExtendWith(SpringExtension.class):
@SpringBatchTest
@SpringJUnitConfig(MyBatchJobConfiguration.class)
public class MyBatchJobTests {
@Autowired
private JobLauncherTestUtils jobLauncherTestUtils;
@Autowired
private JobRepositoryTestUtils jobRepositoryTestUtils;
@BeforeEach
public void setup(@Autowired Job jobUnderTest) {
this.jobLauncherTestUtils.setJob(jobUnderTest);
this.jobRepositoryTestUtils.removeJobExecutions();
}
@Test
public void testMyJob() throws Exception {
// given
JobParameters jobParameters = this.jobLauncherTestUtils.getUniqueJobParameters();
// when
JobExecution jobExecution = this.jobLauncherTestUtils.launchJob(jobParameters);
// then
Assertions.assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus());
}
}
- Since:
- 4.1
- Author:
- Mahmoud Ben Hassine
- See Also: