【问题标题】:Could not autowire JobLauncherTestUtils无法自动装配 JobLauncherTestUtils
【发布时间】:2020-01-14 02:37:15
【问题描述】:

我正在尝试测试一个简单的 spring 批处理应用程序。

使用 Spring Batch 文档作为指南 (found here),我创建了以下测试类:

import org.junit.runner.RunWith;
import org.springframework.batch.test.JobLauncherTestUtils;
import org.springframework.batch.test.context.SpringBatchTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;

import static org.junit.jupiter.api.Assertions.assertNotNull;

@SpringBatchTest
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = BatchConfig.class)
class BatchConfigTest {
    @Autowired
    private JobLauncherTestUtils jobLauncherTestUtils;

    @Test
    void userStep() {
        assertNotNull(jobLauncherTestUtils, "jobLauncherTestUtils should not be null");
    }
}

根据文档@SpringBatchTest 应该注入JobLaucherTestUtils bean。但是,当我运行测试时,断言失败。我也尝试在内部配置类中定义 bean 并得到相同的结果:

    static class TestConfiguration {
        @Autowired
        @Qualifier("userJob")
        private Job userJob;

        @Bean
        public JobLauncherTestUtils jobLauncherTestUtils() {
            JobLauncherTestUtils utils = new JobLauncherTestUtils();
            utils.setJob(userJob);
            return utils;
        }
    }

我有什么遗漏吗?完整的源代码可以在here找到。

【问题讨论】:

  • 您能指定您使用的是哪个版本的 Spring Batch 和 Junit 吗?
  • @MahmoudBenHassine 我正在使用 Spring Batch v4.2.0 和 JUnit 5
  • 好的,谢谢。让我检查一下并尽快回复您。

标签: spring junit spring-batch


【解决方案1】:

我正在使用 Spring Batch v4.2.0 和 JUnit 5

您使用的是用于 JUnit 4 的 @RunWith(SpringRunner.class)。您需要使用 @ExtendWith(SpringExtension.class) 进行 JUnit 5 测试:

@SpringBatchTest
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = BatchConfig.class)
class BatchConfigTest {
   // ...
}

【讨论】:

  • 感谢您指出这一点。我已经更新了代码,但我仍然无法自动装配jobLauncherTestUtils bean。我看到的错误是Could not autowire. No beans of 'JobLauncherTestUtils' type found.
  • 按我的预期工作,这是一个最小的完整示例:github.com/benas/spring-batch-sandbox/tree/master/so59726807
  • 谢谢你的例子。似乎主要问题是我没有为测试定义数据源 bean。在测试特定的配置类中定义数据源并将其包含在@ContextConfiguration 注释中似乎已经成功了。感谢您的所有帮助!
  • 很高兴它有帮助!在这种情况下,请accept the answer
  • 示例链接失效,搜索github,找到正确链接:github.com/benas/spring-batch-lab/tree/master/issues/so59726807
【解决方案2】:

我在 IntelliJ 中看到了同样的错误,并且在运行测试之前花了很长时间研究原因。它被注入得很好,IntelliJ 错误地告诉我 bean 不存在。

:脸:

发布此内容以防有人遇到同样的问题。

【讨论】:

    【解决方案3】:

    我在使用 Spring Batch 4.1.3 和 JUnit 4.12 时遇到了同样的问题。

    @SpringBatchTest 替换为@SpringBootTest 解决了这个问题。

    【讨论】:

      猜你喜欢
      • 2022-01-09
      • 2012-01-27
      • 2016-10-09
      • 2017-08-08
      • 2020-05-04
      • 2014-11-27
      • 1970-01-01
      • 1970-01-01
      • 2018-06-21
      相关资源
      最近更新 更多