【问题标题】:Spring batch test for dynamically created job动态创建作业的春季批处理测试
【发布时间】:2020-09-12 20:44:03
【问题描述】:

在我的应用程序中,我有多个作业所以我创建了动态作业。我在运行此应用程序时没有问题。我想对动态创建的作业进行单元测试。

我想将我的工作设置为 JobLauncherTestUtils 。

@RunWith(SpringRunner.class)
@SpringBatchTest()
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class })
@DirtiesContext(classMode = ClassMode.AFTER_CLASS)
@PropertySource("classpath:application.yml")
public class SpringBatchIntegrationTest {
    @Inject
    private JobRepository jobRepository;
    @Inject
    private JobLauncher mJobLauncher;
    private JobLauncherTestUtils jobLauncherTestUtils;
    @Inject
    BatchJobConfig mBatchJobConfig;
    public void initailizeJobLauncherTestUtils() {
        jobLauncherTestUtils = new JobLauncherTestUtils();
        jobLauncherTestUtils.setJobRepository(jobRepository);
        jobLauncherTestUtils.setJob(mBatchJobConfig.createJob());
        jobLauncherTestUtils.setJobLauncher(mJobLauncher);
    }

这就是我初始化 JobLauncherTestUtils 的方式。当我运行它时,我得到以下错误 创建名为 'jobLauncherTestUtils' 的 bean 时出错:通过方法 'setJob' 参数 0 表达的不满足的依赖关系;谁能告诉我如何对动态作业进行春季批量测试。 我对 Junit 了解不多。我刚开始学习

【问题讨论】:

    标签: java spring-boot unit-testing junit spring-batch


    【解决方案1】:

    @SpringBatchTest 已经在您的测试上下文中添加了一个 JobLauncherTestUtils 类型的 bean(请参阅 Javadoc),因此您不需要自己添加它。

    但是,JobLauncherTestUtils 需要一个作业 bean,而且您似乎没有在测试上下文中定义一个作业 bean。您可以做的是在配置类中定义一个并将其导入您的测试上下文中,例如:

    @RunWith(SpringRunner.class)
    @SpringBatchTest
    @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class })
    @DirtiesContext(classMode = ClassMode.AFTER_CLASS)
    @PropertySource("classpath:application.yml")
    @ContextConfiguration
    public class SpringBatchIntegrationTest {
       @Inject
       private JobRepository jobRepository;
       @Inject
       private JobLauncher mJobLauncher;
       @Inject
       private JobLauncherTestUtils jobLauncherTestUtils;
    
       // No need for initailizeJobLauncherTestUtils
    
       // Add your test method
    
       @Configuration
       @Import(BatchJobConfig.class) // you might need this or not depending on what's defined in BatchJobConfig
       static class MyJobConfiguration {
    
          @Bean
          public Job job(BatchJobConfig mBatchJobConfig) {
             return mBatchJobConfig.createJob();
          }
    
       }
    
    }
    

    【讨论】:

    • 感谢您的回复。我照你说的做了。现在我发现了另一个问题 Error created bean with name 'jobRepositoryTestUtils': Unsatisfied dependencyexpressed through method 'setDataSource' parameter 0;
    • 是的,jobRepositoryTestUtils@SpringBatchTest 添加的另一个实用程序(参见 javadoc),它需要数据源存在于测试上下文中。
    猜你喜欢
    • 2012-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-28
    • 2017-10-06
    • 1970-01-01
    相关资源
    最近更新 更多