If your are using spring and reactive to access data with redis reactively.
Meaning you're having a ReactiveRedisConnectionFactory
(with a RedisConnectionFactory
bean) and a LettuceConnectionFactory
then you may want to follow this approach to set an embedded redis for multiple test classes.
First add the playtika embedded redis to your dependencies:
dependencies {
testCompile("com.playtika.testcontainers:embedded-redis:2.0.9")
}
Then set the redis host and port as the embedded.redis
one in your application.yml (that are generated by the embedded redis as env variable on creation).
spring:
redis:
host: \${embedded.redis.host:localhost}
port: \${embedded.redis.port:6739}
In a bootstrap-redisnoauth.properties
file, set the env variable embedded.redis.requirepass=false
so that it does not require password.
Then in your test use the active profile:
@ActiveProfiles("redisnoauth")
And make sure to have this @TestConfiguration
in your test class as well so that will connect you to the redis spawned on a randomly generated port.
@Category(IntegrationTest.class)
@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("redisnoauth")
public class RedisCacheTest {
@TestConfiguration
static class RedisTestConfiguration {
@Bean
public RedisConnectionFactory redisConnectionFactory(@Value("${spring.redis.host}") String host,
@Value("${spring.redis.port}") int port) {
return new LettuceConnectionFactory(host, port);
}
@Bean
public RedisOperations<String, String> stringKeyAndStringValueRedisOperations(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.setKeySerializer(new StringRedisSerializer(UTF_8));
redisTemplate.setValueSerializer(new StringRedisSerializer(UTF_8));
return redisTemplate;
}
}
@Test
public void myTest() {
// your test
}
}
And it should work smoothly.