【问题标题】:Spring Batch: unit test late bindingSpring Batch:单元测试后期绑定
【发布时间】:2015-01-21 14:29:58
【问题描述】:

我的阅读器配置如下:

<bean name="reader" class="...Reader" scope="step">
    <property name="from" value="#{jobParameters[from]}" />
    <property name="to" value="#{jobParameters[to]}" />
    <property name="pageSize" value="5"/>
    <property name="saveState" value="false" /> <!-- we use a database flag to indicate processed records -->
</bean>

并像这样对其进行测试:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:testApplicationContext.xml"})
@ActiveProfiles({"default","mock"})
@TestExecutionListeners( {StepScopeTestExecutionListener.class })
public class TestLeadsReader extends    AbstractTransactionalJUnit4SpringContextTests {

@Autowired
private ItemStreamReader<Object[]> reader;

public StepExecution getStepExecution() {
    StepExecution execution = MetaDataInstanceFactory.createStepExecution();
    execution.getExecutionContext().putLong("campaignId", 1);
    execution.getExecutionContext().putLong("partnerId", 1);

    Calendar.getInstance().set(2015, 01, 20, 17, 12, 00);
    execution.getExecutionContext().put("from", Calendar.getInstance().getTime());
    Calendar.getInstance().set(2015, 01, 21, 17, 12, 00);
    execution.getExecutionContext().put("to", Calendar.getInstance().getTime());
    return execution;
}

@Test
public void testMapper() throws Exception {
    for (int i = 0; i < 10; i++) {
        assertNotNull(reader.read());
    }
    assertNull(reader.read());
}

现在,虽然 pageSize 和 saveState 已正确注入我的阅读器,但作业参数却没有。根据文档,这就是它需要做的所有事情,我发现的唯一问题是关于使用 jobParameters['from'] 而不是 jobParameters[from]。知道有什么问题吗?

另外,我的reader在进入测试方法之前没有调用open(executionContext)方法,这是不行的,因为我使用那些作业参数来检索一些在调用read方法时需要可用的数据.不过,这可能与上述问题有关,因为有关使用后期绑定进行测试的文档说“读取器已初始化并绑定到输入数据”。

【问题讨论】:

    标签: testing spring-batch late-binding


    【解决方案1】:

    您在测试中将fromto 设置为步骤执行上下文变量。但是在您的应用程序上下文配置中,您将它们作为作业参数检索。您应该在单元测试中将它们设置为作业参数。

    另外,如果您希望调用 open/update/close ItemStream 生命周期方法,您应该执行该步骤。见http://docs.spring.io/spring-batch/trunk/apidocs/org/springframework/batch/test/JobLauncherTestUtils.html#launchStep-java.lang.String-org.springframework.batch.core.JobParameters-

    【讨论】:

    • StepExecution 不提供设置 JobParameters 的方法,而只是检索它们。我已经尝试使用 JoScopeTestExecutionListener 来代替它在其文档中描述的方式,但是在创建执行上下文时收到一个异常,抱怨 TestInstance 是一个类,而需要接口(如果我没记错的话)
    • 而且 JobExecution 也不允许设置 JobParameters,那么这将是正确的方法吗?
    • 上面的答案是正确的,只是我没有注意MetaDataInstanceFactory,它确实提供了一种使用jobParameters创建步骤执行的方法:MetaDataInstanceFactory.createStepExecution(jobParameters)。这个链接也很有帮助:code.google.com/p/springbatch-in-action/source/browse/trunk/…
    猜你喜欢
    • 2019-07-09
    • 1970-01-01
    • 2014-01-30
    • 2012-02-23
    • 1970-01-01
    • 2010-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多