Chris311
Chris311

Reputation: 3992

Testing a Spring Batch SkipListener

I got a SkipListener configured via xml as follows:

<batch:job id="importPersonsJob" job-repository="jobRepository">
    <batch:step id="importPersonStep">
        <batch:tasklet transaction-manager="transactionManager">
            <batch:chunk reader="personItemReader" writer="personItemWriter"
                commit-interval="5" skip-limit="10">
                <batch:skippable-exception-classes>
                    <batch:include class="java.lang.Throwable" />
                </batch:skippable-exception-classes>
            </batch:chunk>
            <batch:listeners>
                <batch:listener ref="skipListener" />
            </batch:listeners>
        </batch:tasklet>
    </batch:step>
    <batch:listeners>
        <batch:listener ref="authenticationJobListener" />
        <batch:listener ref="jobListener" />
    </batch:listeners>
</batch:job>

The implementation of my SkipListener looks like the following:

public class SkipListener {
    @OnSkipInRead
    public void log(final Throwable throwable) throws IOException {
        // make something
    }

    @OnSkipInWrite
    public void log(final Object objectToWrite, final Throwable throwable) throws IOException {
        // make something
    }

    // some dependencies
}

I already asked google how to test this efficiently. Sadly it wasn't so effective. Maybe you can give me a brief hint of how to achieve this.

Upvotes: 1

Views: 2604

Answers (1)

Haim Raman
Haim Raman

Reputation: 12043

I am assuming that you are not taking about unit testing here.

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>

You should add a test application context to use a JobLauncherTestUtils e.g. your test-context.xml will look like

<beans>
    <bean class="org.springframework.batch.test.JobLauncherTestUtils">
        <property name="job" ref="importPersonsJob"/>
    </bean> 
</beans>

Then use spring test junit runner and call JobLauncherTestUtils.launchStep()

 @ContextConfiguration(
         locations=
                 {"classpath:META-INF/application-conext","classpath: test-context.xml"}
    )
    @RunWith(SpringJUnit4ClassRunner.class)
    public class StepWithSkipTest {

        @Autowired
        private JobLauncherTestUtils jobLauncherTestUtils;

        @Test
        public void testStepWithSkip() throws JobInterruptedException{
            JobExecution execution = jobLauncherTestUtils.launchStep("importPersonStep");

        }
    }

Now the test will execute only the step under test.
The tricky part is to fragment your application context xml so it will be testable

Upvotes: 1

Related Questions