Spring Batch

You can find more info on Spring batch on the Spring website.

Installation

If you are using maven, you can add following dependency to your project.

01
02
03
04
05
<dependency>
    <groupId>org.unitils.spring.batch</groupId>
    <artifactId>unitils-spring-batch</artifactId>
    <version>1.0.2</version>
</dependency>

Config

Please create unitils-local.properties, and add springbatch to unitils.modules. Code as following:

01
02
03
04
unitils.modules= [..other modules..], batch
unitils.module.batch.className=org.unitils.spring.batch.BatchModule
unitils.module.batch.enabled=true
unitils.module.batch.runAfter=

Learn by example

01
02
03
04
05
06
07
08
09
10
11
12
13
14
@RunWith(UnitilsJUnit4TestClassRunner.class)
public class SpringBatchTest1 {
 
     
    @BatchTestPlaceHolder
    private BatchTest batchTest;
 
    @Test
    @BatchTestEnvironment(contextFile="spring/batch/jobs/job-hello-world.xml", job="helloWorldJob")
    public void test() throws Exception {
        batchTest.launchJob();
    }
 
}

But there is another possibility to use the contextfile:

@RunWith(UnitilsJUnit4TestClassRunner.class)
@SpringApplicationContext(value={"batchTest.xml"})
public class BatchModuleTest {
...
}

If you do it this way, you don't have to give a spring context file for every test.

With Unitils there are a few annotations:

  • @BatchTestPlaceHolder: This annotation injects a batch Test in the field.
  • @BatchTestEnvironment: You can set a following parameters:
    • contextFile: You should give the name of the Spring application context.
    • parameter: The parameter to send with the job execution, allowing for testing multiple new executions of same job. If true it will send simply a date to the batch execution. If true and the jobParameters are filled in, then it will take those parameters.
    • job: You must choose a job out of the Spring application context.
    • exitCode: The default is 0 and the test will fail if the expected code doesn’t match the actual code.
    • jobParameters: The jobParameters to send to the job execution. If they are not empty they will be used.
    • option: The option to send with the job execution, allowing for testing restart for instance, default it is set to none, meaning no options will be sent to the job execution.

    In this example, the field 'batch' will be injected with a new object of a class that implement the interface BatchTest. In the first example ('testSuccess') we’ve configured that the Spring context file is batchTest.xml and the job is successfulJob. So when the test begins, the context file will be loaded and when we call the launchJob(), successfulJob will be executed.