【发布时间】:2019-07-09 20:33:00
【问题描述】:
我正在尝试创建一个 Junit 测试用例来测试我的批处理作业的单个步骤,该步骤又具有自定义 JdbcCursorItemReader 并将数据写入平面文件。我无法模拟可以注入处理器以将其写入平面文件的数据。请帮忙。
我按照以下链接中的步骤创建了一个测试用例来启动单个步骤:
https://docs.spring.io/spring-batch/trunk/reference/html/testing.html
由于我的阅读器组件是 stepscope,我使用上面链接中第 10.4 节周围的上下文将所需的域对象放入 ExecutionContext 但在启动该步骤时它无法识别相同的步骤,而是执行实际的 SQL 查询,我我正在通过配置 xml 注入。
我的配置 xml 的步骤如下:
<step id="sample-step" next="next-step">
<tasklet>
<chunk reader="customJDBCReader" processor="customProcessor"
writer="customFlatFileItemWriter" commit-interval="XXX" />
</tasklet>
</step>
我的customreader 实现了JdbcCursorItemReader,它定义了一个用于从数据库读取信息的SQL。
在我的单元测试期间,我试图模拟数据,而不是依赖于数据库中的实际数据
private StepExecution execution;
@BeforeStep
public StepExecution getStepExection() {
execution = MetaDataInstanceFactory.createStepExecution();
return execution;
}
@Test
public void testSampleStep() throws UnexpectedInputException, ParseException, Exception {
MyDomainObject domainObject= new MyDomainObject ();
domainObject.setID("sampleID");
domainObject.setName("sampleName");
domainObject.setImage("sampleImage");
execution.getExecutionContext().put("someKey", domainObject);
execution.setReadCount(1);
JobExecution jobExecution = jobLauncherTestUtils.launchStep("sample-step", jobParameters, execution.getExecutionContext());
AssertFile.assertFileEquals(new FileSystemResource(EXPECTED_FILE), new FileSystemResource(OUTPUT_FILE));
}
预期的结果应该是启动步骤需要从executionContext而不是数据库中获取数据以将其写入faltfile。
【问题讨论】:
-
您说您的阅读器是步进范围的。它从执行上下文中消耗了什么?您在使用
StepScopeTestExecutionListener吗?请分享您的阅读器代码以及您的测试类。 -
@MahmoudBenHassine 感谢您的回复,我的读者从配置执行动态 SQL,它返回 n 条记录 w.r.t 我的 MyDomainObject。我确实有 StepScopeTestExecutionListener 但我的 jobLauncherTestUtils 总是执行真正的查询来为我的步骤提供结果。我无法模拟或覆盖我的自定义阅读器的结果。