Unit Testing

As with other application styles, it is extremely important to unit test any code written as part of a batch job. The Spring core documentation covers how to unit and integration test with Spring in great detail, so it will not be repeated here. It is important, however, to think about how to “end to end” test a batch job, which is what this chapter covers. The spring-batch-test project includes classes that facilitate this end-to-end test approach.

Creating a Unit Test Class

For the unit test to run a batch job, the framework must load the job’s ApplicationContext. Two annotations are used to trigger this behavior:

  • @SpringJUnitConfig indicates that the class should use Spring’s JUnit facilities

  • @SpringBatchTest injects Spring Batch test utilities (such as the JobOperatorTestUtils and JobRepositoryTestUtils) in the test context

If the test context contains a single Job bean definition, this bean will be autowired in JobOperatorTestUtils. Otherwise, the job under test should be manually set on the JobOperatorTestUtils.
As of Spring Batch 6.0, JUnit 4 is no longer supported. Migration to JUnit Jupiter is recommended.
  • Java

  • XML

The following Java example shows the annotations in use:

Using Java Configuration
@SpringBatchTest
@SpringJUnitConfig(SkipSampleConfiguration.class)
public class SkipSampleFunctionalTests { ... }