Search code examples
javaunit-testingspring-bootjunitspring-data-redis

Prevent connection to Redis server in unit tests


I am building an app with spring-boot. In order to avoid sticky-session related problems, I put in place a redis session store by adding those lines in pom.xml :

<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>

and those lines in application.properties :

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

It worked like a charm. I was surprised that it worked even if I did not use the annotation @EnableRedisHttpSession. At the beginning, I found it nice.

Problem : I have a Spring configuration for the real application and also a Spring configuration dedicated to unit tests. The Redis connection is useless in the unit test environment and make the test fail if I do not install a Redis server in the test environment.

I could eventually install a Mock Redis as a maven dependency but it would be cleaner if I found a way to disable this useless connection.

Any idea?


Solution

  • To solve this Redis unit test issue I'm using @ConditionalOnProperty and setting a property while running the unit test (testing=true). So, I'm using the following code for session configuration:

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

    And the following code for the unit test:

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