【问题标题】:Spring Batch: Unit testing a custom item readerSpring Batch:对自定义项目阅读器进行单元测试
【发布时间】:2015-03-31 12:48:18
【问题描述】:

我想找到一种方法来对我作为 MultiResourceItemReader 的委托编写的自定义 ItemReader 进行单元测试。

这是我的 Spring Batch XML 配置文件:

<batch:job id="allegati" incrementer="jobParametersIncrementer">
    <batch:step id="allegati-import">
        <batch:tasklet>
            <batch:chunk reader="allegati-reader" writer="allegati-writer" commit-interval="1"/>
        </batch:tasklet>
    </batch:step>
</batch:job>

<bean id="allegati-reader" class="org.springframework.batch.item.file.MultiResourceItemReader" scope="step">
    <property name="resources" value="file:#{jobParameters['FILEPATH']}/*" />
    <property name="delegate" ref="allegati-filereader" />
</bean>

<bean id="allegati-writer" class="org.springframework.batch.item.database.JpaItemWriter">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

<bean id="allegati-filereader" class="it.infogroup.vertenze.porting.reader.AllegatiReader" />

这是我尝试的测试(我要测试的类是 AllegatiReader):

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:jobAllegati.xml"})
@TestExecutionListeners({DependencyInjectionTestExecutionListener.class, StepScopeTestExecutionListener.class})
public class AllegatiTest { 

@Autowired
private JobLauncherTestUtils jobLauncherTestUtils;
@Autowired
private AllegatiReader reader;
@PersistenceContext
protected EntityManager em;

public static final String PARAM_ID = "RUN ID";
public static final String PARAM_FILEPATH = "FILEPATH";
public static final String PARAM_FILEPATH_VALUE = "E:/Test/Vertenze/Porting/Allegati";

public StepExecution getStepExecution() {
    JobParametersBuilder jpb = new JobParametersBuilder();
    jpb.addString(PARAM_FILEPATH, PARAM_FILEPATH_VALUE);
    jpb.addLong(PARAM_ID, System.currentTimeMillis());

    StepExecution execution = MetaDataInstanceFactory.createStepExecution(jpb.toJobParameters());
    return execution;
}

@Test
public void testReader() throws Exception {
    Allegato allegato = reader.read();
    Assert.assertNotNull(allegato);;
}

我的问题是资源(即存在于 FILEPATH 中的文件)没有注入到我的阅读器中。

【问题讨论】:

  • 你能发布你得到的异常吗?
  • @MichaelMinella 我没有遇到特别的例外。简单地说,setResource 方法永远不会被自动调用。我已经通过更改 testReader 方法来“解决”这个问题,以便手动设置资源。

标签: java junit spring-batch


【解决方案1】:

我猜您正在尝试测试委托阅读器(AllegatiReader 类)?如果是这样的话,如果你想使用自动装配,你需要使用 multiresourceitemreader 作为被测 bean

原因

  • multiresourceitemreader 创建完整的委托阅读器 对象(包含资源集)
  • (委托)阅读器 bean 本身不会(不能)作为完全 使用资源配置阅读器

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-23
    • 2012-10-10
    • 2012-03-27
    • 2015-01-23
    • 2014-03-15
    • 2018-05-27
    • 1970-01-01
    相关资源
    最近更新 更多