此版本仍在开发中,尚不被认为是稳定的。对于最新的稳定版本,请使用 Spring Batch 文档 5.2.2spring-doc.cadn.net.cn

单元测试

与其他应用程序样式一样,对编写的任何代码进行单元测试非常重要作为批处理作业的一部分。Spring 核心文档涵盖了如何单元化和集成使用 Spring 进行测试非常详细,因此这里不再重复。然而,重要的是,思考如何“端到端”测试批处理作业,这就是本章所介绍的内容。 这spring-batch-test项目包括促进此端到端测试的类 方法。spring-doc.cadn.net.cn

创建单元测试类

要使单元测试运行批处理作业,框架必须加载作业的ApplicationContext. 两个注释用于触发此行为:spring-doc.cadn.net.cn

  • @SpringJUnitConfig表示类应该使用 Spring 的JUnit 设施spring-doc.cadn.net.cn

  • @SpringBatchTest注入 Spring Batch 测试实用程序(例如JobOperatorTestUtilsJobRepositoryTestUtils) 在测试上下文中spring-doc.cadn.net.cn

如果测试上下文包含单个Jobbean 定义,这个bean 将在JobOperatorTestUtils. 否则,应在JobOperatorTestUtils.

以下 Java 示例显示了正在使用的注释:spring-doc.cadn.net.cn

使用 Java 配置
@SpringBatchTest
@SpringJUnitConfig(SkipSampleConfiguration.class)
public class SkipSampleFunctionalTests { ... }

以下 XML 示例显示了正在使用的注释:spring-doc.cadn.net.cn

使用 XML 配置
@SpringBatchTest
@SpringJUnitConfig(locations = { "/simple-job-launcher-context.xml",
                                    "/jobs/skipSampleJob.xml" })
public class SkipSampleFunctionalTests { ... }

批处理作业的端到端测试

“端到端”测试可以定义为测试批处理作业的完整运行从头到尾。这允许设置测试条件、执行作业、并验证最终结果。spring-doc.cadn.net.cn

考虑一个从数据库读取并写入平面文件的批处理作业示例。测试方法首先使用测试数据设置数据库。它清除了CUSTOMER表,然后插入 10 条新记录。然后测试启动Job通过使用srartJob()方法。 这srartJob()方法由JobOperatorTestUtils类。 这JobOperatorTestUtils类还提供了startJob(JobParameters)方法,它允许测试给出特定参数。 这srartJob()方法 返回JobExecution对象,这对于断言特定信息很有用关于Job跑。 在以下情况下,测试会验证Job以状态COMPLETED.spring-doc.cadn.net.cn

以下列表显示了 Java 配置样式的 JUnit 5 示例:spring-doc.cadn.net.cn

基于 Java 的配置
@SpringBatchTest
@SpringJUnitConfig(SkipSampleConfiguration.class)
public class SkipSampleFunctionalTests {

    @Autowired
    private JobOperatorTestUtils jobOperatorTestUtils;

    private JdbcTemplate jdbcTemplate;

    @Autowired
    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    @Test
    public void testJob(@Autowired Job job) throws Exception {
        this.jobOperatorTestUtils.setJob(job);
        this.jdbcTemplate.update("delete from CUSTOMER");
        for (int i = 1; i <= 10; i++) {
            this.jdbcTemplate.update("insert into CUSTOMER values (?, 0, ?, 100000)",
                                      i, "customer" + i);
        }

        JobExecution jobExecution = jobOperatorTestUtils.startJob();


        Assert.assertEquals("COMPLETED", jobExecution.getExitStatus().getExitCode());
    }
}

以下列表显示了 XML 配置样式的 JUnit 5 示例:spring-doc.cadn.net.cn

基于 XML 的配置
@SpringBatchTest
@SpringJUnitConfig(locations = { "/simple-job-launcher-context.xml",
                                    "/jobs/skipSampleJob.xml" })
public class SkipSampleFunctionalTests {

    @Autowired
    private JobOperatorTestUtils jobOperatorTestUtils;

    private JdbcTemplate jdbcTemplate;

    @Autowired
    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    @Test
    public void testJob(@Autowired Job job) throws Exception {
        this.jobOperatorTestUtils.setJob(job);
        this.jdbcTemplate.update("delete from CUSTOMER");
        for (int i = 1; i <= 10; i++) {
            this.jdbcTemplate.update("insert into CUSTOMER values (?, 0, ?, 100000)",
                                      i, "customer" + i);
        }

        JobExecution jobExecution = jobOperatorTestUtils.startJob();


        Assert.assertEquals("COMPLETED", jobExecution.getExitStatus().getExitCode());
    }
}

测试单个步骤

对于复杂的批处理作业,端到端测试方法中的测试用例可能会变成 不可收拾。 在这些情况下,使用测试用例来测试单个步骤可能会更有用。 这JobOperatorTestUtilsclass 包含一个名为launchStep, 它采用一个步骤名称并仅运行该特定Step. 这种方法允许更有针对性的测试,让测试仅为该步骤设置数据并验证其直接结果。以下示例演示如何使用startStep启动Step按名称:spring-doc.cadn.net.cn

JobExecution jobExecution = jobOperatorTestUtils.startStep("loadFileStep");

测试步进范围组件

通常,在运行时为您的步骤配置的组件使用步骤范围和late 绑定来从步骤或作业执行中注入上下文。这些组件很难作为独立组件进行测试,除非您有办法将上下文设置为步骤中一样 执行。 这是 Spring Batch 中两个组件的目标:StepScopeTestExecutionListenerStepScopeTestUtils.spring-doc.cadn.net.cn

监听器在类级别声明,其工作是创建步骤执行 上下文,如以下示例所示:spring-doc.cadn.net.cn

@SpringJUnitConfig
@TestExecutionListeners( { DependencyInjectionTestExecutionListener.class,
    StepScopeTestExecutionListener.class })
public class StepScopeTestExecutionListenerIntegrationTests {

    // This component is defined step-scoped, so it cannot be injected unless
    // a step is active...
    @Autowired
    private ItemReader<String> reader;

    public StepExecution getStepExecution() {
        StepExecution execution = MetaDataInstanceFactory.createStepExecution();
        execution.getExecutionContext().putString("input.data", "foo,bar,spam");
        return execution;
    }

    @Test
    public void testReader() {
        // The reader is initialized and bound to the input data
        assertNotNull(reader.read());
    }

}

有两个TestExecutionListeners.一种是常规的 Spring Test 框架,它 处理来自配置的应用程序上下文的依赖项注入以注入读取器。 另一个是 Spring BatchStepScopeTestExecutionListener.它的工作原理是寻找一个 测试用例中的工厂方法StepExecution,将其用作 test 方法,就好像该执行在Step在运行时。工厂方法 由其签名检测到(它必须返回StepExecution).如果工厂方法是 未提供,默认值StepExecution被创建。spring-doc.cadn.net.cn

从 v4.1 开始,StepScopeTestExecutionListenerJobScopeTestExecutionListener作为测试执行监听器导入 如果测试类用@SpringBatchTest.前面的测试 示例可以配置如下:spring-doc.cadn.net.cn

@SpringBatchTest
@SpringJUnitConfig
public class StepScopeTestExecutionListenerIntegrationTests {

    // This component is defined step-scoped, so it cannot be injected unless
    // a step is active...
    @Autowired
    private ItemReader<String> reader;

    public StepExecution getStepExecution() {
        StepExecution execution = MetaDataInstanceFactory.createStepExecution();
        execution.getExecutionContext().putString("input.data", "foo,bar,spam");
        return execution;
    }

    @Test
    public void testReader() {
        // The reader is initialized and bound to the input data
        assertNotNull(reader.read());
    }

}

如果您希望步骤作用域的持续时间为 测试方法的执行。对于更灵活但更具侵入性的方法,您可以使用 这StepScopeTestUtils.以下示例计算 上一个示例中显示的阅读器:spring-doc.cadn.net.cn

int count = StepScopeTestUtils.doInStepScope(stepExecution,
    new Callable<Integer>() {
      public Integer call() throws Exception {

        int count = 0;

        while (reader.read() != null) {
           count++;
        }
        return count;
    }
});

模拟域对象

在为 Spring Batch 编写单元和集成测试时遇到的另一个常见问题 components 是如何模拟域对象。一个很好的例子是StepExecutionListener如 以下代码片段显示:spring-doc.cadn.net.cn

public class NoWorkFoundStepExecutionListener implements StepExecutionListener {

    public ExitStatus afterStep(StepExecution stepExecution) {
        if (stepExecution.getReadCount() == 0) {
            return ExitStatus.FAILED;
        }
        return null;
    }
}

该框架提供了前面的侦听器示例,并检查了StepExecution为空读取计数,因此表示未完成任何工作。虽然这个例子是 相当简单,它用于说明您在以下情况下可能遇到的问题类型 您尝试对实现需要 Spring Batch 域的接口的类进行单元测试 对象。请考虑在前面示例中对侦听器的以下单元测试:spring-doc.cadn.net.cn

private NoWorkFoundStepExecutionListener tested = new NoWorkFoundStepExecutionListener();

@Test
public void noWork() {
    StepExecution stepExecution = new StepExecution("NoProcessingStep",
                new JobExecution(new JobInstance(1L, new JobParameters(),
                                 "NoProcessingJob")));

    stepExecution.setExitStatus(ExitStatus.COMPLETED);
    stepExecution.setReadCount(0);

    ExitStatus exitStatus = tested.afterStep(stepExecution);
    assertEquals(ExitStatus.FAILED.getExitCode(), exitStatus.getExitCode());
}

由于 Spring Batch 域模型遵循良好的面向对象原则,因此StepExecution需要一个JobExecution,这需要一个JobInstanceJobParameters,以创建有效的StepExecution.虽然这在固体领域中很好 model,它确实使创建用于单元测试的存根对象变得冗长。为了解决这个问题, Spring Batch 测试模块包括一个用于创建域对象的工厂:MetaDataInstanceFactory.鉴于此工厂,可以更新单元测试以更多 简明,如以下示例所示:spring-doc.cadn.net.cn

private NoWorkFoundStepExecutionListener tested = new NoWorkFoundStepExecutionListener();

@Test
public void testAfterStep() {
    StepExecution stepExecution = MetaDataInstanceFactory.createStepExecution();

    stepExecution.setExitStatus(ExitStatus.COMPLETED);
    stepExecution.setReadCount(0);

    ExitStatus exitStatus = tested.afterStep(stepExecution);
    assertEquals(ExitStatus.FAILED.getExitCode(), exitStatus.getExitCode());
}

前面创建简单StepExecution只是一种方便的方法 工厂内有售。您可以在其 Javadoc 中找到完整的方法列表。spring-doc.cadn.net.cn