【问题标题】:Testing a Spring Batch SkipListener测试 Spring Batch SkipListener
【发布时间】:2014-03-07 15:46:40
【问题描述】:

我通过 xml 配置了一个 SkipListener,如下所示:

<batch:job id="importPersonsJob" job-repository="jobRepository">
    <batch:step id="importPersonStep">
        <batch:tasklet transaction-manager="transactionManager">
            <batch:chunk reader="personItemReader" writer="personItemWriter"
                commit-interval="5" skip-limit="10">
                <batch:skippable-exception-classes>
                    <batch:include class="java.lang.Throwable" />
                </batch:skippable-exception-classes>
            </batch:chunk>
            <batch:listeners>
                <batch:listener ref="skipListener" />
            </batch:listeners>
        </batch:tasklet>
    </batch:step>
    <batch:listeners>
        <batch:listener ref="authenticationJobListener" />
        <batch:listener ref="jobListener" />
    </batch:listeners>
</batch:job>

我的 SkipListener 的实现如下所示:

public class SkipListener {
    @OnSkipInRead
    public void log(final Throwable throwable) throws IOException {
        // make something
    }

    @OnSkipInWrite
    public void log(final Object objectToWrite, final Throwable throwable) throws IOException {
        // make something
    }

    // some dependencies
}

我已经问过谷歌如何有效地测试这个。遗憾的是它没有那么有效。也许你可以给我一个简短的提示,告诉我如何做到这一点。

【问题讨论】:

    标签: java spring unit-testing listener spring-batch


    【解决方案1】:

    我假设您在这里没有进行单元测试。

    Spring Batch 自带一个不错的测试框架。

    将以下内容添加到您的 pom.xml

    <dependency>   
     <groupId>org.springframework.batch</groupId>
        <artifactId>spring-batch-test</artifactId>
        <version>${spring.batch.version}</version>
        <scope>test</scope>
    </dependency>
    

    您应该添加一个测试应用程序上下文以使用 JobLauncherTestUtils,例如你的 test-context.xml 看起来像

    <beans>
        <bean class="org.springframework.batch.test.JobLauncherTestUtils">
            <property name="job" ref="importPersonsJob"/>
        </bean> 
    </beans>
    

    然后使用spring test junit runner并调用JobLauncherTestUtils.launchStep()

     @ContextConfiguration(
             locations=
                     {"classpath:META-INF/application-conext","classpath: test-context.xml"}
        )
        @RunWith(SpringJUnit4ClassRunner.class)
        public class StepWithSkipTest {
    
            @Autowired
            private JobLauncherTestUtils jobLauncherTestUtils;
    
            @Test
            public void testStepWithSkip() throws JobInterruptedException{
                JobExecution execution = jobLauncherTestUtils.launchStep("importPersonStep");
    
            }
        }
    

    现在测试将只执行被测步骤。
    棘手的部分是分割您的应用程序上下文 xml,以便它可以测试

    【讨论】:

      猜你喜欢
      • 2021-08-18
      • 1970-01-01
      • 2011-11-30
      • 2018-09-27
      • 2015-03-24
      • 2020-11-04
      • 1970-01-01
      • 2016-03-16
      • 1970-01-01
      相关资源
      最近更新 更多