防止在单元测试中连接到 Redis 服务器

Prevent connection to Redis server in unit tests

我正在使用 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 依赖项,但如果我找到一种方法来禁用这个无用的连接,它会更干净。

有什么想法吗?

您可以使用 @Profile 注释来完成此操作。您可以使您的 redis 配置仅适用于 NOT 单元测试配置文件。像这样:

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

为了解决这个 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 {
}