@Target(value=TYPE) @Retention(value=RUNTIME) @Documented @Inherited @TestExecutionListeners(listeners={StepScopeTestExecutionListener.class,JobScopeTestExecutionListener.class}, mergeMode=MERGE_WITH_DEFAULTS) @ExtendWith(value=org.springframework.test.context.junit.jupiter.SpringExtension.class) public @interface SpringBatchTest
JobLauncherTestUtils
bean with the
BatchTestContextCustomizer.JOB_LAUNCHER_TEST_UTILS_BEAN_NAME
which can be used
in tests for launching jobs and steps.
JobRepositoryTestUtils
bean
with the BatchTestContextCustomizer.JOB_REPOSITORY_TEST_UTILS_BEAN_NAME
which can be used in tests setup to create or remove job executions.
StepScopeTestExecutionListener
and JobScopeTestExecutionListener
as 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; @Before public void clearJobExecutions() { this.jobRepositoryTestUtils.removeJobExecutions(); } @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 @ContextConfiguration(classes = MyBatchJobConfiguration.class) public class MyBatchJobTests { @@Autowired private JobLauncherTestUtils jobLauncherTestUtils; @@Autowired private JobRepositoryTestUtils jobRepositoryTestUtils; @BeforeEach public void clearJobExecutions() { 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()); } }
It should be noted that JobLauncherTestUtils
requires a
Job
bean and that
JobRepositoryTestUtils
requires a DataSource
bean.
Since this annotation registers a JobLauncherTestUtils
and a
JobRepositoryTestUtils
in the test context, it is expected that the
test context contains a single autowire candidate for a
Job
and a DataSource
(either a single bean definition or one that is
annotated with Primary
).
JobLauncherTestUtils
,
JobRepositoryTestUtils
,
StepScopeTestExecutionListener
,
JobScopeTestExecutionListener