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:

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).

Since:
4.1
Author:
Mahmoud Ben Hassine
See Also: