Search code examples
testinglistenerspring-batchjobs

SpringBatch: Test a JobExecutionListener


I got a JobExecutionListener as follows:

public class JobListener implements JobExecutionListener {

    @Override
    public void beforeJob(final JobExecution jobExecution) {
        // do some work with the jobExecution
    }

    @Override
    public void afterJob(final JobExecution jobExecution) {
        // do some work with the jobExecution
    }
}

I want to write a test for my JobListener and i am wondering myself if i need to mock the JobExecution. Do you think that will be ok, or is there another nice solution to this?


Solution

  • Spring batch comes with a nice testing framework.
    Add the following to your pom.xml

    <dependency>   
     <groupId>org.springframework.batch</groupId>
        <artifactId>spring-batch-test</artifactId>
        <version>${spring.batch.version}</version>
        <scope>test</scope>
    </dependency>
    

    If you want to unit test this class, you may use the org.springframework.batch.test.MetaDataInstanceFactory to create a job context
    e.g.

    JobListener jobListener = new JobListener ()
    //Create a JobExecution (You have 6 overloaded methods choose the one you like)
    JobExecution jobExecution = MetaDataInstanceFactory.createJobExecution(..);
    jobListener.beforeJob(jobExecution);
    jobListener.afterJob(jobExecution);
    

    If you want to make this into an integration test write a snippet job xml that contains some mocked job and use the org.springframework.batch.test.JobLauncherTestUtils
    For more information see http://docs.spring.io/spring-batch/reference/html/testing.html