java - 动态创建作业的 Spring 批量测试

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

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

我想将我的作业设置为 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 表达的依赖关系不满足;谁能告诉我如何对动态作业进行 Spring 批量测试。 我对Junit了解不多。我刚刚开始学习

最佳答案

@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();
      }

   }

}

关于java - 动态创建作业的 Spring 批量测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62015497/

相关文章:

java - 如何禁用在 IntelliJ IDEA 中显示 Spring @Value 注释的值?

mongodb - 为什么在使用 GeoJsonPoint 执行 nearSphere 查询时会出现 CodecConfigurationException?

java - 如何对依赖于 Channel API 的代码进行单元测试(Google App Engine,Java)

java - Nginx:如何将外部请求反向代理到特定的本地主机 URL

java - Spring Aspect 的监控方法

java - 由于来自单元测试的日志文件,Jenkins Maven 发布失败

c# - 使用全局变量的单元测试方法

java - 在 Java 中使用扭曲的子类化构建器模式

java - 无法将 JProfiler 与 Netbeans 中的 Java 项目集成

java - 列表上不区分大小写的搜索(搜索词可以是单词或句子的一部分)