SpringBatch: Test a JobExecutionListener

2019-08-22 03:07发布

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?

1条回答
Juvenile、少年°
2楼-- · 2019-08-22 03:46

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

查看更多
登录 后发表回答