【问题标题】:Spring Boot Integration test mock external dependencySpring Boot Integration 测试模拟外部依赖
【发布时间】:2021-12-13 13:23:13
【问题描述】:

我正在尝试为我的 Spring Boot 应用程序创建集成测试。这个想法是启动一个嵌入式 postgres 数据库并使用 TestRestTemplate 对我的控制器运行 http 调用。

问题是我的项目有一个我们用于 redis 队列的依赖项。

    <dependency>
      <groupId>com.github.sonus21</groupId>
      <artifactId>rqueue-spring-boot-starter</artifactId>
      <version>2.9.0-RELEASE</version>
    </dependency>

我已经尝试模拟出依赖项,并且它们中的大多数都可以工作,但是我猜这个它抱怨是因为它是 @Configuration 而不是 @Component

依赖配置类:

@Configuration
@AutoConfigureAfter({RedisAutoConfiguration.class})
@ComponentScan({"com.github.sonus21.rqueue.web", "com.github.sonus21.rqueue.dao"})
public class RqueueListenerAutoConfig extends RqueueListenerBaseConfig {
    public RqueueListenerAutoConfig() {
    }
...
}

我的测试配置类

@TestConfiguration
public class TestRestTemplateConfig {

    @Bean
    @Primary
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public RqueueListenerAutoConfig rqueueListenerAutoConfig() {
        return Mockito.mock(RqueueListenerAutoConfig.class);
    }

    ....
}

我已经在我的配置类中尝试使用 @AutoConfigureOrder(1),但原来的 RqueueListenerAutoConfig 会在任何事情之前启动,并且我的模拟 bean 还没有被声明。

老实说,在该依赖项上模拟每个服务是一件痛苦的事情,但我还没有找到一种方法来使用单个配置模拟整个依赖项。当我在测试配置文件上时,我尝试不加载依赖项,但由于它运行 spring 上下文,我的代码需要它。

我的测试类有以下配置:

@SpringBootTest
@Import(TestRestTemplateConfig.class)
@ActiveProfiles("test")
public class TestClass {
...
}

有什么线索吗?

谢谢。

【问题讨论】:

  • 这能回答你的问题吗? stackoverflow.com/a/55662387/8209328
  • @Kovsharov 这对我有帮助,现在错误不同了,但至少我没有被阻止,谢谢!
  • 我现在遇到的问题是它试图通过接口将我的模拟转换为其他对象并且它变得混乱。有没有一种方法可以模拟启动所有redis内容的类,这样它最终实际上并没有加载所有配置?我觉得我在兜圈子。

标签: java spring-boot integration-testing spring-bean


【解决方案1】:

试试

@EnableAutoConfiguration(exclude=RqueueListenerAutoConfig.class)

【讨论】:

  • 成功了!我知道必须有一个简单的方法来做到这一点。非常感谢!
猜你喜欢
  • 2021-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-12
  • 1970-01-01
  • 2020-01-16
相关资源
最近更新 更多