【问题标题】:Prevent connection to Redis server in unit tests在单元测试中阻止连接到 Redis 服务器
【发布时间】:2016-06-01 08:35:41
【问题描述】:

我正在使用spring-boot 构建一个应用程序。为了避免与粘滞会话相关的问题,我通过在 pom.xml 中添加这些行来放置一个 redis 会话存储:

<dependency>
  <groupId>org.springframework.session</groupId>
  <artifactId>spring-session</artifactId>
  <version>1.2.0.RELEASE</version>
</dependency>

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-redis</artifactId>
</dependency>

以及 application.properties 中的那些行:

spring.redis.host=localhost
spring.redis.password=secret
spring.redis.port=6379

它就像一个魅力。即使我没有使用注释@EnableRedisHttpSession,它也能正常工作,我感到很惊讶。一开始觉得挺好看的。

问题:我有一个用于实际应用程序的 Spring 配置,还有一个专门用于单元测试的 Spring 配置。 Redis连接在单元测试环境中没有用,如果我在测试环境中没有安装Redis服务器,会导致测试失败。

我最终可以安装一个 Mock Redis 作为 maven 依赖项,但如果我找到一种方法来禁用这个无用的连接,它会更干净。

有什么想法吗?

【问题讨论】:

  • Spring Boot 的 SessionAutoConfiguration 开始使用。您可以在应用程序中排除它(@SpringBootApplication 或属性),请参阅 here
  • @mp911de 仅当我将其应用于应用程序 conf 和测试 conf 时,才添加此功能。如果我仅在应用程序conf上手动添加@EnableRedisHttpSession,它也会被测试配置检测到。您知道如何防止测试配置检测到应用配置上的@EnableRedisHttpSession 吗?
  • 无法从@Enable... 注释中恢复。 Enabled 已启用。我认为个人资料在这里可以为您提供帮助。
  • @mp911de 我找到了第二个问题的解决方案。我从测试配置的组件扫描中排除了应用程序配置并且它有效。您的解决方案适用于问题中暴露的问题,因此您希望发布答案,我会投票并接受它。

标签: java unit-testing spring-boot junit spring-data-redis


【解决方案1】:

为了解决这个 Redis 单元测试问题,我使用了@ConditionalOnProperty 并在运行单元测试时设置了一个属性 (testing=true)。因此,我使用以下代码进行会话配置:

@Configuration
public class SessionConfig {
    @ConditionalOnProperty(name = "testing", havingValue = "false", matchIfMissing = true)
    @EnableRedisHttpSession
    public static class RedisSessionConfig {
    }

    @ConditionalOnProperty(name = "testing", havingValue = "true")
    @EnableSpringHttpSession
    public static class MapSessionConfig {
        @Bean
        public SessionRepository<ExpiringSession> sessionRepository() {
            return new MapSessionRepository();
        }
    }
}

单元测试的代码如下:

@RunWith(SpringRunner.class)
@TestPropertySource(properties = "testing=true")
@SpringBootTest(classes = Application.class)
public class MyTest {
}

【讨论】:

    【解决方案2】:

    您可以使用@Profile 注释来做到这一点。您可以使您的 redis 配置仅适用于非单元测试配置文件。像这样:

    @Configuration
    @Profile("!" + Constants.SPRING_PROFILE_UNITTEST)
    public class RedisConfiguration {
        @Bean
        public RedisTemplate getRedisTemplate() {...}
    }
    

    【讨论】:

      猜你喜欢
      • 2021-10-29
      • 1970-01-01
      • 2017-09-21
      • 2021-06-23
      • 2013-02-25
      • 2017-03-01
      • 2021-05-15
      • 1970-01-01
      • 2010-09-08
      相关资源
      最近更新 更多