Java Reference
In-Depth Information
@Test
public void testCarFileReader() throws Exception {
((ItemStream) carFileReader).open(new ExecutionContext());
for(int i = 0; i < 5; i++) {
assertEquals(carFileReader.read(), records.get(i));
}
assertNull(carFileReader.read());
}
}
CarFileReaderIntegrationTest uses a facility you haven't seen up to now. MetaDataInstanceFactory
is a class provided by Spring Batch for creating mocks of the Spring Batch domain objects. Under most
situations, I would strongly recommend using just Mockito to limit the coupling between your unit tests
and Spring; but in this case, things are a bit different.
Spring Batch requires a StepExecution object. However, what it does with it is rather complex, and
to mock that with Mockito would require you to have knowledge of the inner workings of Spring Batch.
This type of situation isn't something you want to mock using Mockito, so you use Spring's
MetaDataInstanceFactory to create the mock instead.
As mentioned earlier, there are two ways to test a Spring Batch component that is defined in the
step scope. The first, being the listener approach you just saw, is non-invasive and lets you apply the
step scope to all the test methods in your test case. But if you only need it for one or two of the test
methods in your test case, Spring Batch provides a utility to wrap your execution in a step. Testing the
same component, carFileReader , you can execute it in the scope of a step by using StepScopeTestUtils .
Listing 12-16 shows the unit test updated to use StepScopeTestUtils instead of the listeners to simulate a
step.
Listing 12-16. Using StepScopeTestUtils
package com.apress.springbatch.chapter12;
import static org.junit.Assert.assertEquals;
import java.util.concurrent.Callable;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemStream;
import org.springframework.batch.test.MetaDataInstanceFactory;
import org.springframework.batch.test.StepScopeTestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import
org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
 
Search WWH ::




Custom Search