Testing
A chunk of problems (and solutions)
Testing Spring Batch can be tricky, there isn't vast documentation nor Junit5 support. Indeed we have several problems to make integration tests to run, so we decided to build unit tests only (the failing integration tests are committed as a separate branch here)
The extension
We had to emulate the job run so we decided to build a new extension and we continue using this custom pattern where the test case is the implementation of the interface the extension model is waiting. It sounds difficult but it isn't, so let's focus on SpringBatchChunkUpdateFeesTests.java.
@ExtendWith(SpringExtension.class)
public class SpringBatchChunkUpdateFeesTests implements TestDoubleBatchHelper {
...
@RegisterExtension
public final SpringBatchChunkExtension<UVALoanFee, UVALoanFee> extension = new SpringBatchChunkExtension<UVALoanFee, UVALoanFee>();
We have seen this before, we are using the Spring Extension for easy mocking in cases we have "autowired" fields and we would implement a custom interface needed for our custom extension: SpringBatchChunkExtension.java.
public class SpringBatchChunkExtension<R, P> implements Extension {
public List<P> simulateSimpleRun(ItemReader<R> reader, ItemProcessor<R, P> processor, ItemWriter<P> writer,
TestDoubleBatchHelper helper)
throws UnexpectedInputException, ParseException, NonTransientResourceException, Exception {
helper.mockInjectionsReadOk();
helper.mockInjectionsProcessOk();
helper.mockInjectionsWriteOk();
List<P> written = new ArrayList<P>();
boolean keepIterating = true;
while (keepIterating) {
R actual = reader.read();
if (actual == null) {
keepIterating = false;
} else {
P processed = processor.process(actual);
if(processed!=null) {
List<P> processedList = new ArrayList<P>();
processedList.add(processed);
written.add(processed);
writer.write(processedList);
}
}
}
return written;
}
}
The code is really straightforward, it invokes a mock for each part of the chunk batch and calls each chunk simulating the job launcher.
And that's it, now we have to use the extension (and implement the mocking) as follows
@Test
public void testChunkJobShouldWork()
throws UnexpectedInputException, ParseException, NonTransientResourceException, Exception {
List<UVALoanFee> written = extension.simulateSimpleRun(reader, processor, writer, this);
List<UVALoanFee> expected = buildToBeWrittenFakeResult();
assertThat(written).isEqualTo(expected);
}
Last updated
Was this helpful?