【问题标题】:How to mock custom JdbcCursorItemReader during individual step unit testing on Spring Batch?如何在 Spring Batch 的单个步骤单元测试期间模拟自定义 JdbcCursorItemReader?
【发布时间】: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 总是执行真正的查询来为我的步骤提供结果。我无法模拟或覆盖我的自定义阅读器的结果。

标签: spring-boot spring-batch


【解决方案1】:

你的期望是错误的。如果该步骤使用JdbcBatchItemWriter,此阅读器仍将在测试期间发出 SQL 查询,无论您是否在执行上下文中模拟数据。步骤的输入数据与执行上下文中存储的数据不同。

在这种情况下,我建议在您的测试中使用嵌入式数据库并使用一些虚拟数据填充它。

希望这会有所帮助。

【讨论】:

  • 感谢您的更新!是的,我最近也意识到了这一点,将尝试使用嵌入式数据库模拟我的数据来解决这个问题。
  • 太好了,很高兴它有帮助。在这种情况下,请accept the answer。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-12
  • 2018-09-27
  • 2023-04-01
  • 2023-03-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多